<template>
  <t-card :bordered="false">
    <div class="form-step-container">
      <t-button @click="add">新增</t-button>
      <t-tabs v-model="tabIndex" @change="tabIndexChange">
        <t-tab-panel value="1" label="线下活动" :destroyOnHide="false"></t-tab-panel>
        <t-tab-panel value="2" label="调查问卷" :destroyOnHide="false"></t-tab-panel>
        <t-tab-panel value="3" label="公益捐赠" :destroyOnHide="false"></t-tab-panel>
        <t-tab-panel value="4" label="学习培训" :destroyOnHide="false"></t-tab-panel>
      </t-tabs>
      <t-table
        rowKey="index"
        :data="list"
        :columns="columns"
        :stripe="true"
        :bordered="false"
        :hover="true"
        size="large"
        table-layout="auto"
        cellEmptyContent="-"
        :pagination="pagination"
      >
<!--        <template #activity_image="{ row }">-->
<!--          <div style="text-align: center;">-->
<!--            <t-image-->
<!--              :src="$store.state.user.apiUrl+row.activity_image"-->
<!--              fit="contain"-->
<!--              :style="{ width: '120px',margin:'0 auto'}"-->
<!--            />-->
<!--          </div>-->
<!--        </template>-->
        <template #money="{ row }">
         <div v-if="row.activity_type==4">
           <div v-if="row.money>0">
             <span>￥</span>
             <span>{{row.money}}</span>
           </div>
           <div v-if="row.money==0">
             <span>免费</span>
           </div>
         </div>
          <div v-if="row.activity_type!=4">
            -
          </div>
        </template>
        <template #activity_type="{ row }">
          <div style="text-align: center;">
            <span v-if="row.activity_type==1">线下活动</span>
            <span v-if="row.activity_type==2">调查问卷</span>
            <span v-if="row.activity_type==3">公益捐赠</span>
            <span v-if="row.activity_type==4">学习培训</span>
          </div>
        </template>
        <template #select="{ row }">
          <t-space size="24px">
            <t-button v-if="row.activity_type==1"  @click="openInfo(row)">报名详情</t-button>
            <t-button v-if="row.activity_type==2" theme="default" @click="openQuestionnairefind(row)">新增题目</t-button>
            <t-button v-if="row.activity_type==2"  theme="primary" @click="openQuestionnaireUpdate(row)">编辑题目</t-button>
            <t-button v-if="row.activity_type==2" theme="success">查看调查</t-button>
            <t-button v-if="row.activity_type==3" @click="openInfo(row)">捐赠详情</t-button>
            <t-button v-if="row.activity_type==4" @click="openInfo(row)">付费详情</t-button>
            <t-button theme="warning" @click="edit(row)">编辑</t-button>
            <t-popconfirm content="确认删除吗" @confirm="del(row)">
              <t-button theme="danger">删除</t-button>
            </t-popconfirm>
          </t-space>
        </template>
      </t-table>
      <div style="margin-top: 30px">
        <t-pagination
          :total="pagination.total"
          :page-size="pagination.size"
          @current-change="onCurrentChange"
          :showPageSize="false"
        ></t-pagination>
      </div>
    </div>
    <t-dialog header="报名详情" :confirmBtn="null" :visible="infoMode" :onClose="onCloseMy" width="45%" top="50px">
      <t-table
        rowKey="index"
        :data="info_list"
        :columns="info_columns"
        :stripe="true"
        :bordered="false"
        :hover="true"
        size="large"
        table-layout="auto"
        cellEmptyContent="-"
      >
        <template #photo_image="{ row }">
          <img :src="$store.state.user.apiUrl+row.photo_image" style="width: 50px;height: 50px">
        </template>
      </t-table>
      <div style="margin-top: 30px">
        <t-pagination
          :total="info_pagination.total"
          :page-size="info_pagination.size"
          @current-change="onCurrentChangeInfo"
          :showPageSize="false"
        ></t-pagination>
      </div>
    </t-dialog>
    <t-dialog :header="isEdit?'编辑活动':'新增活动'" :visible="addMode" :onClose="onCloseMy" @confirm="onSubmit"
              width="45%" top="20px">
      <t-form>
        <t-form-item label="活动标题" name="activity_name">
          <t-input placeholder="请输入活动标题" v-model="addForm.activity_name"/>
        </t-form-item>
        <t-form-item label="活动简介" name="activity_desc">
          <t-input placeholder="请输入活动简介" v-model="addForm.activity_desc"/>
        </t-form-item>
        <t-form-item label="活动地址" name="activity_location">
          <t-input placeholder="请输入活动地址" v-model="addForm.activity_location"/>
        </t-form-item>
        <t-form-item label="活动类别" name="activity_type">
          <t-select v-model="addForm.activity_type">
            <t-option key="1" label="线下活动" value="1"/>
            <t-option key="2" label="调查问卷" value="2"/>
            <t-option key="3" label="公益捐赠" value="3"/>
            <t-option key="4" label="学习培训" value="4"/>
          </t-select>
        </t-form-item>
        <t-form-item v-if="addForm.activity_type==4" label="付费金额" name="money">
          <t-input placeholder="请输入付费金额（0为免费）" v-model="addForm.money"/>
        </t-form-item>
        <t-form-item label="活动简介" name="activity_desc">
          <div style="border: 1px solid #ccc;">
            <!-- 工具栏 -->
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              mode="default"
              :editor="editor"
              :defaultConfig="toolbarConfig"
            />

            <Editor
              style="height: 200px"
              v-model="addForm.activity_content"
              :defaultConfig="editorConfig"
              mode="default"
              @onCreated="(e) => onCreated(e)"
            />
          </div>
        </t-form-item>
        <t-form-item label="活动主图">
          <t-upload
            :action="$store.state.user.apiUrl+'/api/common/upload'"
            v-model="addForm.activity_image_show"
            theme="image"
            tips="请选择单张图片文件上传"
            accept="image/*"
            :format-response="formatResponse"
          ></t-upload>
        </t-form-item>
        <t-form-item label="活动开始时间" name="activity_start_time">
          <t-date-picker :clearable="true" :style="{ width: '480px' }" placeholder="活动开始时间"
                         :enableTimePicker="true" :allow-input="false"
                         v-model="addForm.activity_start_time"></t-date-picker>
        </t-form-item>
        <t-form-item label="活动结束时间" name="activity_end_time">
          <t-date-picker :clearable="true" :style="{ width: '480px' }" placeholder="活动结束时间"
                         :enableTimePicker="true" :allow-input="false"
                         v-model="addForm.activity_end_time"></t-date-picker>
        </t-form-item>
      </t-form>
    </t-dialog>

    <t-dialog header="新增题目" :visible="questionnaireMode" :onClose="onCloseMy" @confirm="onSubmitQuestionnaire"
              width="45%" top="20px">
      <div style="height: 600px;overflow-y: scroll;">
        <t-form>
          <t-card v-for="(item,index) in questionnaireData" style="margin-bottom: 10px">
            <template >
              <t-form-item label="类型">
                <t-radio-group v-model="item.type">
                  <t-radio :value="1">单选题</t-radio>
                  <t-radio :value="2">多选题</t-radio>
                  <t-radio :value="3">问答题</t-radio>
                </t-radio-group>
              </t-form-item>
              <t-form-item label="排序">
                <t-input v-model="item.wight" type="number" placeholder="请输入排序"></t-input>
              </t-form-item>
              <t-form-item label="题目">
                <t-input v-model="item.title" placeholder="请输入题目"></t-input>
              </t-form-item>
              <t-form-item :label="op.name" v-for="(op,opi) in item.option" v-if="item.type!=3">
                <t-input v-model="op.val" placeholder="请输入选项答案"></t-input>
                <t-button @click="delOptionItem(index,opi)" theme="danger" size="small" variant="base" style="margin-left: 20px">X</t-button>
              </t-form-item>
              <div style="text-align: center" v-if="item.type!=3">
                <t-button @click="addOption(index)" theme="primary" variant="base">添加一个选项</t-button>
              </div>
              <div style="position:absolute;right: 20px;top: 20px">
                <t-button @click="delOptionTop(index)" theme="danger" size="small" variant="base" style="margin-left: 20px">删除题目</t-button>
              </div>
            </template>
          </t-card>

          <div style="text-align: center;margin-top: 30px">
            <t-button @click="addQuestionnaire()" theme="warning" variant="base">添加一个题目</t-button>
          </div>
        </t-form>
      </div>
    </t-dialog>
    <t-dialog header="编辑题目" :visible="questionnaireUpdateMode" :confirmBtn="null"  :onClose="onCloseMy" @confirm="onCloseMy"
              width="45%" top="20px">
      <div style="height: 600px;overflow-y: scroll;">
        <t-form>
          <t-card v-for="(item,index) in questionnaire" style="margin-bottom: 10px">
            <template >
              <t-form-item label="类型">
                <t-radio-group v-model="item.type">
                  <t-radio :value="1">单选题</t-radio>
                  <t-radio :value="2">多选题</t-radio>
                  <t-radio :value="3">问答题</t-radio>
                </t-radio-group>
              </t-form-item>
              <t-form-item label="排序">
                <t-input v-model="item.wight" placeholder="请输入排序"></t-input>
              </t-form-item>
              <t-form-item label="题目">
                <t-input v-model="item.title" placeholder="请输入题目"></t-input>
              </t-form-item>
              <t-form-item  v-for="(op,opi) in item.option" :label="op.name" v-if="item.type!=3">
                <t-input v-model="op.val" placeholder="请输入选项答案"></t-input>
                <t-button @click="delUpdateOptionItem(index,opi)" theme="danger" size="small" variant="base" style="margin-left: 20px">X</t-button>
              </t-form-item>
              <div style="text-align: center" v-if="item.type!=3">
                <t-button @click="addOption(index)" theme="primary" variant="base">添加一个选项</t-button>
              </div>
              <div style="position:absolute;right: 20px;top: 20px">
                <t-popconfirm content="确认删除吗" @confirm="delUpdateOptionTop(index,item)">
                  <t-button theme="danger" size="small" variant="base" style="margin-left: 20px">删除题目</t-button>
                </t-popconfirm>
              </div>
              <div style="text-align: center;margin-top: 20px">
                <t-button theme="success" @click="updateOption(item)" variant="base">保存</t-button>
              </div>
            </template>
          </t-card>
        </t-form>
      </div>
    </t-dialog>
  </t-card>

</template>
<script lang="ts">
import store from "@/store";
import {Editor, Toolbar} from '@wangeditor/editor-for-vue';

export default {
  components: {Editor, Toolbar},
  data() {
    return {
      questionnaireData: [{
        type: 1, title: '', wight:0,option: [{name: 'A', val: ""}, {name: 'B', val: ""}]
      }],
      tabIndex: '1',
      visible: false,
      infoMode: false,
      addForm: {
        money:'0',
        activity_name: '',
        activity_desc: '',
        activity_image_show: [],
        activity_image: '',
        activity_start_time: '',
        activity_end_time: '',
        activity_content: '',
        activity_location: '',
        activity_type: null,
      },
      addMode: false,
      isEdit: false,
      editID: 0,
      infoId: 0,
      info_list: [],
      info_columns: [
        {colKey: 'photo_image', title: '证件照', align: 'center'},
        {colKey: 'nikename', title: '姓名', align: 'center'},
        {colKey: 'phone', title: '手机号', align: 'center'},
        {colKey: 'position', title: '职位', align: 'center'},
        {colKey: 'application_time', title: '报名时间', align: 'center'},
      ],
      info_pagination: {
        page: 1,
        size: 10,
        total: 0,
      },
      list: [],
      columns: [
        {colKey: 'activity_name', title: '活动标题', align: 'center',width: 200,},
        {colKey: 'activity_type', title: '活动类别', width: 200, align: 'center'},
        {colKey: 'money', title: '付费金额', align: 'center'},
        {colKey: 'activity_start_time', title: '活动开始时间', align: 'center'},
        {colKey: 'activity_end_time', title: '活动结束时间', align: 'center'},
        {colKey: 'activity_location', title: '活动地点', align: 'center'},
        {colKey: 'select', title: '操作', width: 200, align: 'center'},
      ],
      pagination: {
        page: 1,
        size: 10,
        total: 0,
      },
      editor: null,
      toolbarConfig: {
        showLinkImg: false,
        uploadImgShowBase64: true,
        excludeKeys: [
          'insertVideo', // 删除视频
          'uploadVideo',
          'group-video',
          'insertImage',// 删除网络图片上传
          'insertLink',// 删除链接
          'insertTable',// 删除表格
          'codeBlock',// 删除代码块
        ]
      },
      editorConfig: {
        placeholder: '',
        readOnly: false, // 是否只允许阅读，不可编辑
        autoFocus: true,
        MENU_CONF: {
          uploadImage: {
            server: store.state.user.apiUrl + '/api/common/upload',
            fieldName: 'file',
            customInsert(res: any, insertFn: InsertFnType) {  // TS 语法
              // customInsert(res, insertFn) {                  // JS 语法
              // res 即服务端的返回结果
              console.log(res);
              // 从 res 中找到 url alt href ，然后插入图片
              insertFn(res.data.fullurl, '', '')
            },
          }
        }
      },
      questionnaireMode: false,//问题模态框
      questionnaire: [],//问题列表
      questionnaireId:0,
      questionnaireUpdateMode:false,
    }
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  mounted() {
    this.getList();
  },
  methods: {
    //删除编辑题目里的单条选项
    delUpdateOptionTop(index,item){
      console.log(item);
      if(this.questionnaire.length<=1){
        this.$message.error('至少保留一个题目');
        return;
      }
      this.questionnaire.splice(index, 1);
      this.$request
        .post("/questionnaire/topicDel", {
          id: item.id,
        })
        .then((res) => {
          console.log(res);
          if(res.code==1){
            //删除成功
            this.$message.success('删除成功');
          }else{
            this.$message.error(res.msg);
          }
          this.openQuestionnaireUpdate({id:item.activity_id});
        })
        .catch((e) => {
          console.log(e);
        });
    },
    delOptionTop(index){
      if(this.questionnaireData.length<=1){
        this.$message.error('至少保留一个题目');
        return;
      }
      this.questionnaireData.splice(index, 1);
    },
    delUpdateOptionItem(index,opIndex){
      if( this.questionnaire[index].option.length<=2){
        this.$message.error('至少保留两个选项');
        return;
      }
      this.questionnaire[index].option.splice(opIndex, 1);
      this.questionnaire[index].option.forEach((item, index) => {
        item.name = String.fromCharCode(65 + index);
      });
    },
    delOptionItem(index,opIndex){
      if( this.questionnaireData[index].option.length<=2){
        this.$message.error('至少保留两个选项');
        return;
      }
      this.questionnaireData[index].option.splice(opIndex, 1);
      this.questionnaireData[index].option.forEach((item, index) => {
        item.name = String.fromCharCode(65 + index);
      });
    },
    updateOption(d){
      var option = d.option;
      console.log(option);
      const transformedArray = [];
      for (const key in option) {
        transformedArray.push({
          name: key,
          val: option[key].name, // 这里的`key`1111是根据你的示例构建的，可以根据实际需求调整
        });
      }
      let jsonString = d;
      this.$request
        .post("/questionnaire/topicEdit", {
          topic: JSON.stringify(jsonString),
          id:d.id,
        })
        .then((res) => {
          console.log(res);
          if(res.code==1){
            this.$message.success('保存成功');
          }else{
            this.$message.error(res.msg);
          }
          this.openQuestionnaireUpdate({id:d.activity_id});
        })
        .catch((e) => {
          console.log(e);
        });
    },
    addQuestionnaire() {
      var newItem = {
        type: 1, title: '',wight:0, option: [{name: 'A', val: ""}, {name: 'B', val: ""}]
      };
      this.questionnaireData.push(newItem);
    },
    addOption(index) {
      const newItem = {
        name: String.fromCharCode(65 + this.questionnaireData[index].option.length),
        val: ""
      };
      this.questionnaireData[index].option.push(newItem);
    },
    onSubmitQuestionnaire(){
      let jsonString = JSON.stringify(this.questionnaireData);
      console.log(jsonString);
      this.$request
        .post("/questionnaire/topicAdd", {
          activity_id: this.questionnaireId,
          topic:jsonString
        })
        .then((res) => {
          console.log(res);
          if(res.code==1){
            this.$message.success('添加成功');
          }else{
            this.$message.error(res.msg);
          }
          this.onCloseMy();
        })
        .catch((e) => {
          console.log(e);
        });
    },
    openQuestionnaireUpdate(d){
      this.$request
        .post("/questionnaire/questionnairefind", {
          activity_id: d.id,
        })
        .then((res) => {
          console.log(res);
          this.questionnaire = res.data;
          this.questionnaireUpdateMode = true;
        })
        .catch((e) => {
          console.log(e);
        });
    },
    openQuestionnairefind(d) {
      this.questionnaireId=d.id;
      this.questionnaireMode = true;
    },
    onCurrentChangeInfo(d) {
      this.info_pagination.page = d;
      this.openInfo();
    },
    onCurrentChange(d) {
      this.pagination.page = d;
      this.getList();
    },
    openInfo(d) {
      this.infoMode = true;
      this.infoId = d.id;
      this.$request
        .post("/application/find", {
          application_id: this.infoId,
          page: this.info_pagination.page,
          size: this.info_pagination.size
        })
        .then((res) => {
          console.log(res);
          if (res.code == 1) {
            this.info_list = res.data.ret;
            this.info_pagination.total = res.data.count;
          }

        })
        .catch((e) => {
          console.log(e);
        });
    },
    formatResponse(res) {
      console.log(res);
      this.addForm.activity_image = res.data.url;
      return {url: res.data.fullurl};
    },
    onCreated(editor) {
      this.editor = Object.seal(editor);
    },
    del(d) {
      console.log(d);
      this.$request
        .post('/activity/del', {id: d.id})
        .then((res) => {
          if (res.code == 1) {
            this.$message.success(res.msg);
            this.getList();
          } else {
            this.$message.error(res.msg);
          }
          console.log(res);
        })
        .catch((e) => {
          console.log(e);
        });
    },
    add() {
      this.addMode = true;
      this.isEdit = false;
      this.addForm = {
        money:0,
        activity_name: '',
        activity_desc: '',
        activity_image_show: [],
        activity_image: '',
        activity_start_time: '',
        activity_end_time: '',
        activity_content: '',
        activity_location: '',
        activity_type: null,
      };
    },
    edit(d) {
      console.log(d);
      this.addForm.id = d.id;
      this.addForm.activity_name = d.activity_name;
      this.addForm.activity_desc = d.activity_desc;
      this.addForm.activity_image_show = [{url: store.state.user.apiUrl + d.activity_image}];
      this.addForm.activity_image = d.activity_image;
      this.addForm.activity_start_time = d.activity_start_time;
      this.addForm.activity_end_time = d.activity_end_time;
      this.addForm.activity_location = d.activity_location;
      this.addForm.activity_content = d.activity_content;
      this.addForm.activity_type = d.activity_type;
      this.addForm.money = d.money;
      this.addMode = true;
      this.isEdit = true;
    },
    tabIndexChange(d) {
      console.log(d);
      this.pagination.page = 1;
      this.getList();
    },
    getList() {
      this.$request
        .post("/activity", {page: this.pagination.page, size: this.pagination.size, activity_type: this.tabIndex})
        .then((res) => {
          console.log(res);
          if (res.code == 1) {
            this.list = res.data.ret;
            this.pagination.total = res.data.count;
          }

        })
        .catch((e) => {
          console.log(e);
        });
    },
    onSubmit() {
      console.log(this.addForm);
      if (this.addForm.activity_name == '') {
        this.$message.error('活动标题不能为空');
        return;
      }
      if (this.addForm.activity_desc == '') {
        this.$message.error('活动简介不能为空');
        return;
      }
      if (this.addForm.activity_type == null) {
        this.$message.error('活动类别不能为空');
        return;
      }
      if (this.addForm.activity_image == '') {
        this.$message.error('活动图片不能为空');
        return;
      }
      if (this.addForm.activity_content == '') {
        this.$message.error('活动详情不能为空');
        return;
      }
      if (this.addForm.activity_start_time == '') {
        this.$message.error('活动开始时间不能为空');
        return;
      }
      if (this.addForm.activity_end_time == '') {
        this.$message.error('活动结束时间不能为空');
        return;
      }
      if (this.addForm.activity_location == '') {
        this.$message.error('活动地址不能为空');
        return;
      }
      console.log(this.addForm);
      var url = '/activity/add';
      if (this.isEdit) {
        url = '/activity/update';
      }
      this.$request
        .post(url, this.addForm)
        .then((res) => {
          console.log(res);
          if (res.code == 1) {
            this.$message.success(res.msg);
            this.addMode = false;
            this.getList();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },

    onCloseMy() {
      this.addMode = false;
      this.infoMode = false;
      this.questionnaireMode = false;
      this.questionnaireUpdateMode=false;
    },
  }
}
</script>
<style>
::-webkit-scrollbar {
  display: none;
}
</style>
<style src="@wangeditor/editor/dist/css/style.css"></style>
