<template>
  <div class="edu-training-edit">
    <DialogCom :title="'培训任务临时登记'" @close="onHide" :visible.sync="isShow" width="960px">
      <div class="page-body">
        <el-form :model="formData" :rules="formDataRules" size="small" ref="newTask" label-position="right"
                 label-width="120px">
          <el-row>

            <!-- 培训主题 -->
            <el-col :span="12">
              <el-form-item prop="title" label="任务名称">
                <el-input
                  v-model="formData.title"
                  :maxlength="32"
                  placeholder="请输入任务名称"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="培训类型" prop="type">
                <el-select style="width: 100%" v-model="formData.type" placeholder="请选择培训类型">
                  <el-option v-for="dict in dict.type.edu_training_type" :key="dict.value" :label="dict.label"
                             :value="parseInt(dict.value)"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item  prop="trainingStartDateTime" label="培训开始时间">
                <el-date-picker style="width:100%" required v-model="formData.trainingStartDateTime" :picker-options="startDatepickerOptions"
                                format="yyyy-MM-dd HH:mm"
                                type="datetime" placeholder="选择培训开始时间"  @change="startDateChanged">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="trainingEndDateTime" label="培训结束时间">
                <el-date-picker style="width:100%" required v-model="formData.trainingEndDateTime" :picker-options="endDatepickerOptions" @change="endDateChanged"
                                format="yyyy-MM-dd HH:mm"
                                type="datetime" placeholder="选择培训结束时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <!--            <el-col :span="12">
                          <el-form-item label="机构类型" prop="execOrgType">
                            <el-select style="width: 100%" v-model="formData.execOrgType" placeholder="请选择执行机构类型"
                                       @change="execOrgTypeChanged()">

                              <el-option v-for="dict in getUserOrgType" :key="dict.value" :label="dict.label"
                                         :value="parseInt(dict.value)"></el-option>

                            </el-select>
                          </el-form-item>
                        </el-col>
                        <el-col :span="12">
                          <el-form-item v-show="formData.execOrgType" label="培训机构" prop="planExecOrgIdList">
                            <org-tree-select
                              v-model="formData.planExecOrgIdList"
                              :queryData="formData.execOrgType"
                              ref="orgTreeSelect"
                              :enabledCheckOrgTypes="formData.execOrgType"
                              :disable="true">
                            </org-tree-select>
                          </el-form-item>
                        </el-col>-->
            <!-- 内容 -->
            <el-col :span="24">
              <el-form-item prop="content" label="培训内容">
                <k-textarea v-model="formData.content" placeholder="请输入培训内容" :length="2000"/>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item prop="note" label="培训总结">
                <k-textarea v-model="formData.note" placeholder="请输入培训总结" :length="2000"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="absenceList" label="参会人员">
                <k-select :multiple="true" style="width: 100%" v-model="formData.absenceList" url="/user/find/all"
                          :params="{ orgId: formData.orgId }" placeholder="请选择参会人员"
                          @select="absenceUserSelectChanged"></k-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="absentList" label="缺席人员">
                <k-select :multiple="true"  style="width: 100%" v-model="formData.absentList" url="/user/find/all"
                          :params="{ orgId: formData.orgId }" @select="absentUserSelectChanged"
                          placeholder="请选择缺席人员">
                </k-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>

            <el-col :span="24">
              <el-form-item prop="imageList" label="培训图片">
                <imgUpload ref="uploadimage" type="more" :value="formData.imageList"
                           @input="imageListChanged"></imgUpload>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="培训资料" prop="fileList">
                <K-file-upload ref="upload" :defaultValue="formFileListDefualtValue" v-model="formData.fileList"/>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="">
                <el-button type="primary" @click="showSelectFile">选取知识库文件</el-button>
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmit">确 定</el-button>
        <el-button @click="onHide">取 消</el-button>
<!--        <el-button type="primary" @click="onSave">暂存</el-button>-->

      </div>
    </DialogCom>
    <DialogSelectFile
      ref="DialogSelectFile"
      :defaultSelect=defaultSelect
      @select="fileSelected"
      :orgId="orgId"
    ></DialogSelectFile>
  </div>
</template>

<script>
import {mapState, mapMutations} from "vuex";
import {addEduTask, getEduTask, recordEduTask} from "@/api/core/edu/eduTask";
import dayjs from "dayjs";
import KTextarea from "@/components/common/textarea.vue";
import KSelect from "@/components/common/userselect.vue";
import imgUpload from "@/components/ImageUpload/index.vue";
import OrgTreeSelect from '@/components/orgTreeSelect'
import DialogSelectFile from "../plan/dialog.select.file.vue"
import KFileUpload from "@/components/K-FileUpload/index.vue";

export default {
  dicts: ['edu_type', 'edu_task_status', 'sys_org_type','edu_training_type'],
  components: {KTextarea, KFileUpload, KSelect, imgUpload, OrgTreeSelect, DialogSelectFile},
  data() {
    const params = this.$route.params;
    return {
      id: params ? params.id : null,
      isShow: false,
      formData: this.reset(),
      formDataRules: {
        title: [{required: true, message: "请输入任务名称"}],
        type: [{required: true, message: "请输入培训类型"}],
        content: [{required: true, message: "请输入培训内容"}],
        absenceList: [{required: true, type: "array", message: "请选择参会人员"}],
        trainingStartDateTime: [{required: true, message: "请选择培训开始时间"}],
        trainingEndDateTime: [{required: true, message: "请选择培训结束时间"}],
        note: [{required: true, message: "请输入培训总结"}],
        imageList: [{required: true, message: "请上传培训图片"}],
        // fileList: [{required: true, message: "请上传培训文件"}],
      },
      startDatepickerOptions: {
        disabledDate(time) {
          return false;
        },
      },
      endDatepickerOptions: {
        disabledDate: this.endDisabledDate,
      },
      orgId: null,
      defaultSelect: [],
      formFileListDefualtValue: [],
    };
  },
  props: {},
  watch: {},
  computed: {
    ...mapState(["loginUser", "org",]),
    getUserOrgType() {
      console.log("computed allSysOrgTypes", this.dict.type.sys_org_type, this.$store.getters.orgType);
      let tempArry = [];
      this.dict.type.sys_org_type.forEach(x => {
        if (Number(x.value) >= this.$store.getters.orgType) {
          tempArry.push(x);
        }
      });
      // console.log("computed getUserOrgType",tempArry);
      return tempArry;
    }
  },
  methods: {
    ...mapMutations([]),
    reset(other = {}) {
      return {
        // hostId: null,
        // recorderId: null,
        trainingStartDateTime: null,
        trainingEndDateTime: null,
        // dueCount: null,
        // actualCount: null,
        type: null,
        content: null,
        title: null,
        eduJobId: null,
        imageList: "",
        absenceList: [],
        absentList: [],
        orgList: [],
        fileList: [],
        ...other,
      };
    },
    /*async refresh(id, other) {
      // this.formData = id
      //   ? await this.$api.eduTraining.one(id)
      //   : this.reset(other);

      if (!id) {
        this.reset(other);
        return;
      }
      let _this = this;
      getEduTask(id).then(response => {
        this.loading = false;
        // _this.formData = response.data;
        if (response.data.taskUserList) {
          let list1 = response.data.taskUserList.filter((element) =>
            element.type === 1
          );
          console.log("list1", list1)
          response.data.absenceList = list1 ? list1.map((a) => {
              return a.userId;
            })
            : [];

          let list2 = response.data.taskUserList.filter((element) =>
            element.type === 2
          );
          console.log("list2", list2)
          response.data.absentList = list2 ? list2.map((a) => {
              return a.userId;
            })
            : [];
        } else {
          response.data.absenceList = [];
          response.data.absentList = [];
        }

        if (response.data.imageList == null) {
          response.data.imageList = "";
        }
        if (response.data.fileList == null) {
          response.data.fileList = [];
        }
        this.formData = response.data;
      })
      console.log("getEduTask", this.formData);
    },*/
    async show(id, other = {}) {
      this.isShow = true;
    },
    imageListChanged(list) {
      this.formData.imageList = list;
      console.log("imageListChanged", this.formData.imageList);
    },
    showSelectFile() {
      this.$refs["DialogSelectFile"].show();
    },
    fileSelected(list) {
      if (!list) return;
      let tempArry = [];
      let fileNameList=[]
      let addFileNameList=[]
      this.formData.fileList.forEach(x => {
        let fileObj= JSON.parse(x);
        fileNameList.push(fileObj.name);
      })
      list.forEach(x => {
        tempArry.forEach(s => {
          addFileNameList.push(JSON.parse(s).name);
        })
        x.fileList.forEach(y => {
          let fileObj= JSON.parse(y);
          if (fileNameList.indexOf(fileObj.name) == -1&&addFileNameList.indexOf(fileObj.name) == -1) {
            tempArry.push(y);
          }
        })
      })
      if (this.formData.fileList) {
        this.formFileListDefualtValue = this.formData.fileList.concat(tempArry);
      } else {
        this.formFileListDefualtValue = tempArry;
      }

    },
    absentUserSelectChanged(list) {
      console.log(list);
      // 将类型为2的数据删除
      if (this.formData.taskUserList) {
        this.formData.taskUserList = this.formData.taskUserList.filter(x => x.type == 1);
      } else {
        this.formData.taskUserList = [];
      }
      let tempList = list.map(x => {
        return {
          userId: x.id,
          userName: x.name,
          type: 2
        }
      })
      if (!tempList) return;
      this.formData.taskUserList = this.formData.taskUserList.concat(tempList);
      console.log("absentUserSelectChanged", list, this.formData.taskUserList);
    },
    absenceUserSelectChanged(list) {
      // 将类型为1的数据删除
      if (this.formData.taskUserList) {
        this.formData.taskUserList = this.formData.taskUserList.filter(x => x.type == 2);
      } else {
        this.formData.taskUserList = [];
      }
      let tempList = list.map(x => {
        return {
          userId: x.id,
          userName: x.name,
          type: 1
        }
      });
      if (!tempList) return;
      this.formData.taskUserList = this.formData.taskUserList.concat(tempList);
      // console.log("absenceUserSelectChanged", list, this.formData.taskUserList,this.formData.absenceList);
      // this.formData.absenceList=list.map(item=>item.id);

      // console.log("absenceUserSelectChanged", list, this.formData.taskUserList,this.formData.absenceList);
    },
    // 事件
    onHide() {
      this.isShow = false;
      this.formData = this.reset();
      this.$refs["uploadimage"].clearFiles();
      this.$refs["upload"].clearFiles();
    },
    async onSave() {
      if (!this.validatePerson()) {
        this.$message.error("参与人员与缺席人员重复，请重新选择!");
        return;
      }
      //判断trainingStartDateTime大于trainingEndDateTime就返回
      if (dayjs(this.formData.trainingStartDateTime).isAfter(dayjs(this.formData.trainingEndDateTime))) {
        this.$message.error("培训开始时间不能大于培训结束时间!");
        return;
      }
      let request = {submitType: 1, ...this.formData};
      delete request.absenceList;
      delete request.absentList;

      if (request.trainingStartDateTime)
        request.trainingStartDateTime = dayjs(request.trainingStartDateTime).format('YYYY-MM-DD HH:mm:ss')

      if (request.trainingEndDateTime)
        request.trainingEndDateTime = dayjs(request.trainingEndDateTime).format('YYYY-MM-DD HH:mm:ss')
      // if(request.imageList)
      //   request.imageList=request.imageList.split(',').map(x=>{return x;});
      // request.taskUserList = [];
      recordEduTask(request).then((v) => {
        this.$emit("success", this.formData);
        this.onHide();
        this.$modal.msgSuccess("培训登记暂存成功");
      });
    },
    async onSubmit() {
      //console.log("onSubmit this.formData", this.formData)
      await this.$refs.newTask.validate();
      //判断trainingStartDateTime大于trainingEndDateTime就返回
      if (dayjs(this.formData.trainingStartDateTime).isAfter(dayjs(this.formData.trainingEndDateTime))) {
        this.$message.error("培训开始时间不能大于培训结束时间!");
        return;
      }
      // this.formData.taskUserList=[];
      console.log("onSubmit this.formData", this.formData)
      console.log(this.formData.taskUserList);
      this.formData.taskUserList = this.formData.taskUserList ? this.formData.taskUserList : []
      if (this.formData.taskUserList.length == 0 || this.formData.taskUserList.filter(item => item.type == 1).length == 0) {
        this.$message.error("参与人员不能为空，请重新选择!");
      } else if (!this.validatePerson()) {
        this.$message.error("参与人员与缺席人员重复，请重新选择!");
      } else {
        let request = {submitType: 2, ...this.formData};
        delete request.absenceList;
        delete request.absentList;

        if (request.trainingStartDateTime) {
          request.trainingStartDateTime = dayjs(request.trainingStartDateTime).format('YYYY-MM-DD HH:mm:ss')
        }

        if (request.trainingEndDateTime) {
          request.trainingEndDateTime = dayjs(request.trainingEndDateTime).format('YYYY-MM-DD HH:mm:ss')
        }

        // request.taskUserList = [];
        recordEduTask(request).then((v) => {
          this.$emit("success", this.formData);
          this.onHide();
          this.$modal.msgSuccess("培训登记提交成功");
        });
        // this.$emit("success");
        // this.onHide();
      }
    },
    validatePerson() {
      for (let i = 0; i < this.formData.absenceList.length; i++) {
        let absence = this.formData.absenceList[i];
        if (this.formData.absentList.indexOf(absence) >= 0) {
          return false;
        }
      }
      return true;
    },
    uploadTriggerEvent(value) {
    },

    endDisabledDate(time) {
      //小于开始日期禁止选择
      let startDate = new Date();
      startDate.setTime(startDate.getTime() - 3600 * 1000 * 24);
      if (this.formData.trainingStartDateTime) {
        startDate = new Date(dayjs(this.formData.trainingStartDateTime).format('YYYY-MM-DD'));
        startDate.setTime(startDate.getTime() - 3600 * 1000 * 24);
      }
      return time.getTime() < new Date(startDate).getTime()

    },
    startDateChanged(time) {
      console.log("startDateChanged", time, this.formData.trainingStartDateTime, this.formData.trainingEndDateTime)
      if (dayjs(this.formData.trainingStartDateTime).isAfter(dayjs(this.formData.trainingEndDateTime))) {
        this.formData.trainingEndDateTime = this.formData.trainingStartDateTime;
        console.log("trainingEndDateTime", this.formData.trainingEndDateTime)
      }
    },
    endDateChanged(time) {
      console.log("startDateChanged", time, this.formData.trainingStartDateTime, this.formData.trainingEndDateTime)
      if (dayjs(this.formData.trainingStartDateTime).isAfter(dayjs(this.formData.trainingEndDateTime))) {
        this.formData.trainingStartDateTime = this.formData.trainingEndDateTime;
        console.log("trainingEndDateTime", this.formData.trainingEndDateTime)
      }
    },
    execOrgTypeChanged(row) {
      this.$refs['orgTreeSelect'].clear();
      this.initRoleList(this.form.execOrgType);
      // this.form.planExecOrgIdList = [];
    },
  },
  mounted() {
  },
};
</script>

<!-- <style lang="less">
.edu-training-edit {
}
</style> -->
