<template>
  <div v-loading="pageLoading" class="app-container">
    <card-table :delProp="['createTime']" :loading="loading" :modalData="trainingList" :searchParams="queryParams"
                :tableSearch="true" labelWidth="120px" @columnSearch="handleQuery" @pagination="getList"
                @selection-change="handleSelectionChange" @resetList="resetQuery">
      <template #operations="{ selections }">
        <el-button v-hasPermi="['train:list:add']" icon="el-icon-plus" size="mini" type="primary"
                   @click="handleAdd">{{ $t('trainList.addTrain') }}
        </el-button>
        <el-button v-hasPermi="['train:list:export']" icon="el-icon-download" size="mini" plain
                   @click="handleExport">{{ $t('common.export') }}
        </el-button>
      </template>
      <template #default="{ list }">
        <el-table-column align="center" type="selection" width="55"/>
        <el-table-column align="center" fixed label="No." type="index" width="50"/>
        <!--培训名称-->
        <Column :label="$t('trainList.trainingName')" :searchParams="queryParams" :showSearch="true" fixed
                prop="trainName"/>
        <!--状态-->
        <Column :label="$t('trainList.state')" prop="trainStatus"
                :searchDict="dict.type.train_status"
                :searchParams="queryParams"
                :showSearch="true" searchType="select" select-more selectProp="trainStatusList">
          <template #default="{ row }">
            <ColorDictTag :bgc="statusColorMap[row.trainStatus].bgc"
                          :label="convertStatus(row.trainStatus)"
                          :label-color="statusColorMap[row.trainStatus].color"
            />
          </template>
          <!--          <template #default="{ row }">-->
          <!--            <span>{{ row.trainStatusName }}</span>-->
          <!--          </template>-->
        </Column>
        <!--培训类别-->
        <Column :label="$t('trainList.trainingCategory')" prop="trainType"
                :searchDict="dict.type.training_category"
                :searchParams="queryParams"
                :showSearch="true" searchType="select" select-more selectProp="trainTypeList">
          <template #default="{ row }">
            <span>{{ row.trainTypeName }}</span>
          </template>
        </Column>
        <!--培训对象 -->
        <!--        <Column :label="$t('trainList.trainingTargets')" :searchParams="queryParams"-->
        <!--                :showSearch="true"-->
        <!--                prop="trainingTargets">-->
        <!--        </Column>-->
        <!--开始时间-->
        <Column :label="$t('trainList.startTime')" prop="startDate" :searchParams="queryParams"
                :showSearch="true" searchType="dateRange" prop-start="startDateS" prop-end="startDateE">

        </Column>
        <!--结束时间-->
        <Column :label="$t('trainList.endTime')" prop="endDate" :searchParams="queryParams"
                :showSearch="true" searchType="dateRange" prop-start="endDateS" prop-end="endDateE">

        </Column>
        <!--是否考核-->
        <Column :label="$t('trainList.whetherToAssess')" :searchDict="dict.type.train_whether_to_assess"
                :searchParams="queryParams"
                :showSearch="true" prop="assessFlag"
                searchType="select">
          <template #default="{ row }">
            <span>{{ row.assessFlagName }}</span>
          </template>
        </Column>
        <!--培训完成率-->
        <Column :label="$t('trainList.trainingCompletionRate') + '(%)'" prop="trainingCompletionRate"
                :searchParams="queryParams" :showSearch="true"/>
        <Column :label="$t('trainList.assessmentCompletionRate') + '(%)'" prop="assessmentCompletionRate"
                :searchParams="queryParams" :showSearch="true">
          <template #default="{ row }">
            <span v-if="row.assessFlag === '0'">-</span>
          </template>
        </Column>
        <!--发布人-->
        <Column :label="$t('trainList.publisher')" prop="createByName" :searchParams="queryParams" :showSearch="true"/>
        <!--发布时间-->
        <Column :label="$t('trainList.releaseTime')" prop="createTime" :searchParams="queryParams"
                :showSearch="true" searchType="dateRange">
        </Column>
        <!--备注-->
        <Column :label="$t('trainList.remarks')" prop="remark"/>

        <Column :label="$t('common.operate')" :min-width="250" :showSearch="true" fixed="right" searchType="operate">
          <template #default="{ row }">
            <el-button v-hasPermi="['train:list:view']" icon="el-icon-view" size="mini"
                       type="text" @click="handleView(row)">{{ $t('common.view') }}
            </el-button>
            <el-button v-if="row.trainStatus === '01'" v-hasPermi="['train:list:terminate']" icon="el-icon-video-pause"
                       size="mini"
                       type="text" @click="handleTerminate(row)">{{ $t('trainList.terminate') }}
            </el-button>
            <el-button v-if="row.trainStatus === '00'" v-hasPermi="['train:list:edit']" icon="el-icon-edit" size="mini"
                       type="text" @click="handleUpdate(row)">{{ $t('common.edit') }}
            </el-button>
            <el-button v-if="row.trainStatus === '00'" v-hasPermi="['train:list:delete']" icon="el-icon-delete"
                       size="mini"
                       type="text" @click="handleDelete(row)">{{ $t('common.delete') }}
            </el-button>
            <el-button v-if="row.trainStatus !== '01' && row.trainStatus !== '00'" v-hasPermi="['train:list:addAgain']"
                       icon="el-icon-circle-plus-outline" size="mini"
                       type="text" @click="handleAddAgain(row)">{{ $t('trainList.addAgain') }}
            </el-button>
          </template>
        </Column>
      </template>
    </card-table>


  </div>
</template>

<script>

import {parseTime} from "@/utils/ruoyi";
import Column from "@/components/element/table/Column.vue";
import DatePicker from "@/components/element/form/items/DatePicker.vue";
import {getUser, listUser} from '@/api/system/user'
import CardTable from "@/components/element/table/CardTable.vue";
import DatabaseDialog from "@/views/train/trainlist/detail/databaseDialog.vue";
import {listTrain, getTrain, addTrain, updateTrain, delTrain, terminateTrain} from '@/api/train/train'

import ImportModal from "@/components/ImportModal/index.vue";
import ColorDictTag from "@/views/crmManagement/lead/ColorDictTag/index.vue";

const statusColorMap = {
  '00': {
    color: '#FFC500',
    bgc: 'rgba(255,200,12,0.12)'
  },
  '01': {
    color: '#24CA5D',
    bgc: 'rgba(24,199,84,0.12)'
  },
  '02': {
    color: '#8B71FD',
    bgc: 'rgba(139,113,253,0.12)'
  },
  '03': {
    color: '#D71943',
    bgc: '#FAEDED'
  },
}
export default {
  name: "TrainList",
  components: {ColorDictTag, ImportModal, CardTable, DatePicker, Column, DatabaseDialog},
  dicts: ['train_whether_to_assess', 'training_category', 'train_status', 'train_question_type'],
  data() {
    return {
      statusColorMap: statusColorMap,
      // 遮罩层
      loading: false,
      pageLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        state: undefined,
        trainingCategory: undefined,
        trainingTargets: undefined,
        startDate: undefined,
        endDate: undefined,
        assessFlag: undefined,
        trainingCompletionRate: undefined,
        createByName: undefined,
        createTime: undefined,
        remark: undefined,
      },

      // 主数据
      trainingList: [],

    };
  },
  created() {
    this.getList();
  },
  watch: {
    '$route'(to, from) {
      if (to.path === '/train/trainlist/') {
        this.getList()
      }
    }
  },
  methods: {
    convertStatus(status) {
      if (!status) return '-'
      return this.dict.type.train_status.filter(item => item.value === status)[0].label
    },
    parseTime,
    // 培训列表获取
    getList() {
      this.loading = true;
      let {trainStatus, trainType, createTime, startDate, endDate, ...params} = this.queryParams;
      listTrain(params).then(response => {
        console.log("response=====>", response);
        this.trainingList = response.rows
        this.queryParams.total = response.total
        this.trainingList.forEach(item => {
          item.trainTypeName = this.dict.label.training_category[item.trainType];
          item.assessFlagName = this.dict.label.train_whether_to_assess[item.assessFlag];
          item.trainStatusName = this.dict.label.train_status[item.trainStatus];
        });
      }).finally(() => {
        this.loading = false;
      })
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
      this.countryOptions = [];
      this.areaTree = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      const resetFields = ['trainName', 'trainStatus', 'trainType', 'startDate', 'endDate', 'assessFlag', 'trainingCompletionRate',
        'createByName', 'createTime', 'remark', 'startDateS', 'startDateE', 'endDateS', 'endDateE', 'beginTime', 'endTime', 'trainStatusList',
        'trainTypeList', 'assessmentCompletionRate'];
      resetFields.forEach(field => {
        this.$set(this.queryParams, field, null);
      });
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    async handleAdd() {
      await this.$tab.closePage({name: 'AddTrain', path: '/train/trainlist/detail/addTrain'})
      await this.$tab.openPage(this.$t('trainList.addTrain'), '/train/trainlist/detail/addTrain')
    },

    /** 修改按钮操作 */
    async handleUpdate(row) {
      await this.$tab.closePage({name: 'AddTrain', path: '/train/trainlist/detail/addTrain'})
      let query = {
        id: row.id
      };
      this.$tab.openPage(this.$t('trainList.editTrain'), '/train/trainlist/detail/addTrain', query)
    },
    /** 再次发起*/
    async handleAddAgain(row) {
      await this.$tab.closePage({name: 'AddTrain', path: '/train/trainlist/detail/addTrain'})
      let query = {
        id: row.id,
        type: 'addAgain'
      };
      this.$tab.openPage(this.$t('trainList.addAgain'), '/train/trainlist/detail/addTrain', query)
    },
    // 查看
    handleView(row) {
      // this.$router.push(`/train/trainlist/detail/trainDetail/${row.id}`);
      this.$tab.openPage(this.$t('trainList.trainDetail'), `/train/trainlist/detail/trainDetail/${row.id}`)

    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      try {
        const trainIds = row.id || this.ids;
        await this.$modal.confirm(this.$t('common.isDelete'));
        this.pageLoading = true;
        await delTrain(trainIds);
        this.$modal.msgSuccess(this.$t('common.deleteSuccess'));
      } catch (error) {
        // 处理错误
      } finally {
        this.pageLoading = false;
        this.getList()
      }
    },

    /** 终止培训 */
    async handleTerminate(row) {
      try {
        const trainIds = row.id || this.ids;
        await this.$modal.confirm(this.$t('trainList.isTerminate'));
        this.pageLoading = true;
        console.log("trainIds", trainIds)
        await terminateTrain(trainIds);
        this.$modal.msgSuccess(this.$t('common.deactivatSuccess'));
      } catch (error) {
        console.log("error", error)
        // 处理错误
      } finally {
        this.pageLoading = false;
        this.getList()
      }
    },

    /** 导出按钮操作 */
    // todo 导出，有条件时会报错，应该是数组的问题，待解决
    handleExport() {
      let {trainStatus, trainType, createTime, startDate, endDate, ...params} = this.queryParams;
      console.log("params", params)
      const fileName = this.$t('trainList.trainExportFileName') + parseTime(new Date(), '{y}{m}{d}') + '.xlsx'
      this.download('train/train/export', {
        params,
      }, fileName)
    },

  }
};
</script>

<!--style-->
<style lang="scss" scoped>

::v-deep .edit-dialog {
  .el-dialog__body {
    min-height: 50vh;
    max-height: 75vh;
    overflow: auto;
    padding: 10px 10px;
  }

  .el-dialog__footer {
    padding: 10px 50px 20px 50px;
  }

  .el-form-item--medium .el-form-item__content, .el-form-item--medium .el-form-item__label {
    line-height: 25px;
  }

  .el-form--label-top .el-form-item__label {
    padding: 0;
  }

  .el-form .el-row:last-child .el-form-item {
    margin-bottom: 0;
  }

}


.w-100 {
  width: 100%;
}

/* 更多 按钮 样式 start */
@import "@/assets/styles/element-variables.scss";

.el-dropdown-menu {
  padding: 8px 0;

  .el-dropdown-menu__item {
    padding: 0 20px;
    color: $--color-primary;
  }

  .el-dropdown-menu__item + .el-dropdown-menu__item {
    margin-top: 5px;
  }
}

::v-deep .el-dropdown-menu__item i {
  margin-right: 12px !important;
}

/* 更多 按钮 样式 end */

</style>
