<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="form" label-position="right"
                 label-width="120px" label-prefix=":">
          <el-row>
            <!-- 演练主题 -->
            <el-col :span="24">
              <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="category">
                <el-select style="width: 100%" v-model="formData.category" placeholder="请选择演练类型">
                  <el-option v-for="dict in dict.type.core_drill_category" :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 label="演练项目" prop="type">
                <el-select style="width: 100%" v-model="formData.type" placeholder="请选择演练项目">
                  <el-option v-for="dict in dict.type.core_drill_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="drillSite" label="演练地点">
                <el-input v-model="formData.drillSite" placeholder="请输入演练地点" :length="50"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="drillStartTime" label="演练开始时间">
                <el-date-picker style="width: 100%" required v-model="formData.drillStartTime"
                                :picker-options="startDatepickerOptions"
                                format="yyyy-MM-dd HH:mm"
                                type="datetime" placeholder="选择日期" @change="startDateChanged" width="180">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="drillEndTime" label="演练结束时间">
                <el-date-picker style="width: 100%" required v-model="formData.drillEndTime"
                                format="yyyy-MM-dd HH:mm"
                                :picker-options="endDatepickerOptions" @change="endDateChanged"
                                type="datetime" placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :span="24">

              <el-form-item prop="presetCase" label="预设案由">
                <div style="display: flex;justify-content: flex-end; margin-bottom: 10px">
                  <el-button type="primary" @click="selectMaterials">参考演练范本库</el-button>
                </div>
                <k-textarea v-model="formData.presetCase" placeholder="请输入预设案由" :length="2000"/>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item prop="drillSituation" label="演练情况">
                <k-textarea v-model="formData.drillSituation" placeholder="请输入演练情况" :length="2000"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item  prop="comment" label="点评总结" >
                <k-textarea style="width: 100%;" v-model="formData.comment" placeholder="请输入点评总结" :length="200"/>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item prop="absenceList" label="参演人员">
                <k-select :multiple="true" 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" v-model="formData.absentList" url="/user/find/all"
                          :params="{ orgId: formData.orgId }" @select="absentUserSelectChanged"
                          placeholder="请选择缺席人员">
                </k-select>
              </el-form-item>
            </el-col>
            <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="24">
              <el-form-item label="演练资料" prop="fileList">
                <K-file-upload ref="upload" :defaultValue="formFileListDefualtValue" v-model="formData.fileList"/>
              </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>
    <dialog-drill-dictionary-select
      ref="DialogDrillDictionarySelect"
      :defaultSelect=defaultSelect
      @select="drillDictionarySelect"
      :orgId="this.$store.getters.orgId">
    </dialog-drill-dictionary-select>
  </div>
</template>

<script>
import {mapState, mapMutations} from "vuex";
import {getDrillTask, recordDrillTask} from "@/api/core/drill/drillTask";
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 KFileUpload from "@/components/K-FileUpload/index.vue";
import DialogDrillDictionarySelect from "@/views/core/drill/task/dialog.select.drillDictionary.vue";
export default {
  components: {KTextarea, KSelect, imgUpload,KFileUpload,DialogDrillDictionarySelect},
  data() {
    const params = this.$route.params;
    return {
      id: params ? params.id : null,
      isShow: false,
      formData: this.reset(),
      formDataRules: {
        title: [{required: true, message: "请输入任务名称"}],
        category: [{required: true, message: "请输入演练类型"}],
        drillStartTime: [{required: true, message: "请选择演练开始时间"}],
        drillEndTime: [{required: true, message: "请选择演练结束时间"}],
        drillSite: [{required: true, message: "请输入演练地点"}],
        type: [{required: true, message: "请选择演练项目"}],
        presetCase: [{required: true, message: "请输入预设案由"}],
        drillSituation: [{required: true, message: "请输入演练情况"}],
        comment: [{required: true, message: "请输入点评总结"}],
        absenceList: [{required: true, type: "array", message: "请选择参与人员", trigger: ['blur', 'change']}],
        imageList: [{required: true, message: "请上传演练图片"}],
        // fileList: [{required: true, message: "请上传演练资料"}],
      },
      startDatepickerOptions: {
        disabledDate(time) {
          return false;
        },
      },
      endDatepickerOptions: {
        disabledDate: this.endDisabledDate,
      },
      drillTypeOptions: [],
      formFileListDefualtValue: [],
      defaultSelect: [],
    };
  },
  dicts: ["core_drill_type","core_drill_type","core_drill_category"],
  props: {},
  watch: {},
  computed: {
    ...mapState(["loginUser", "org"]),
  },
  methods: {
    ...mapMutations([]),
    reset(other = {}) {
      return {
        drillStartTime: null,
        drillEndTime: null,
        content: "",
        drillSite: "",
        type: null,
        title: "",
        eduJobId: null,
        imageList: "",
        absenceList: [],
        absentList: [],
        orgList: [],
        fileList: [],
        presetCase:null,
        ...other,
      };
    },
    async refresh(id, other) {
      if (!id) {
        this.reset(other);
        return;
      }
      getDrillTask(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("getDrillTask", this.formData);
    },
    async show(id, other = {}) {
      this.isShow = true;
    },
    imageListChanged(list) {
      this.formData.imageList = list;
      console.log("imageListChanged", this.formData.imageList);
    },
    absentUserSelectChanged(list) {
      // // 将类型为2的数据删除
      // if (this.formData.absentList) {
      //   this.formData.absentList = this.formData.absentList.filter(
      //     (x) => x.type == 1
      //   );
      // } else {
      //   this.formData.absentList = [];
      // }
      // let tempList = list.map((x) => {
      //   return {
      //     userId: x.id,
      //     userName: x.name,
      //     type: 2,
      //   };
      // });
      // if (!tempList) return;
      // this.formData.absentList = this.formData.absentList.concat(tempList);
      // console.log("absentUserSelectChanged", list, this.formData.absentList);
      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.absenceList) {
      //   this.formData.absenceList = this.formData.absenceList.filter(
      //     (x) => x.type == 2
      //   );
      // } else {
      //   this.formData.absenceList = [];
      // }
      // let tempList = list.map((x) => {
      //   return {
      //     userId: x.id,
      //     userName: x.name,
      //     type: 1,
      //   };
      // });
      // if (!tempList) return;
      // this.formData.absenceList = this.formData.absenceList.concat(tempList);
      // console.log("absenceUserSelectChanged", list, this.formData.absenceList);
       // 将类型为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);
    },
    // 事件
    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;
    //   }
    //   let request = {submitType: 1, ...this.formData};
    //   if (request.drillStartTime)
    //     request.drillStartTime = dayjs(request.drillStartTime).format("YYYY-MM-DD HH:mm:ss");
    //   if (request.drillEndTime)
    //     request.drillEndTime = dayjs(request.drillEndTime).format("YYYY-MM-DD HH:mm:ss");
    //   recordDrillTask(request).then((v) => {
    //     this.$emit("success", this.formData);
    //     this.onHide();
    //     this.$modal.msgSuccess("培训登记暂存成功");
    //   });
    // },
    async onSubmit() {
      await this.$refs.form.validate();
      console.log("onSubmit this.formData", this.formData);
      // if (!this.validatePerson()) {
      //   this.$message.error("参与人员与缺席人员重复，请重新选择!");
      // }
      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.drillStartTime)
          request.drillStartTime = dayjs(request.drillStartTime).format("YYYY-MM-DD HH:mm:ss");
        if (request.drillEndTime)
          request.drillEndTime = dayjs(request.drillEndTime).format("YYYY-MM-DD HH:mm:ss");

        recordDrillTask(request).then((v) => {
          this.$emit("success", this.formData);
          this.onHide();
          this.$modal.msgSuccess("演练登记提交成功");
        });
      }
    },
    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.drillStartTime) {
        startDate = new Date(
          dayjs(this.formData.drillStartTime).format("YYYY-MM-DD")
        );
        startDate.setTime(startDate.getTime() - 3600 * 1000 * 24);
      }
      return time.getTime() < new Date(startDate).getTime();
    },
    endDateChanged(time) {
      console.log("startDateChanged", time, this.formData.drillStartTime, this.formData.drillEndTime)
      if (dayjs(this.formData.drillStartTime).isAfter(dayjs(this.formData.drillEndTime))) {
        this.formData.drillStartTime = this.formData.drillEndTime;
        console.log("trainingEndDateTime", this.formData.drillEndTime)
      }
    },
    startDateChanged(time) {
      console.log(
        "startDateChanged",
        time,
        this.formData.drillStartTime,
        this.formData.drillEndTime
      );
      if (
        dayjs(this.formData.drillStartTime).isAfter(
          dayjs(this.formData.drillEndTime)
        )
      ) {
        this.formData.drillEndTime = this.formData.drillStartTime;
        console.log("trainingEndDateTime", this.formData.drillEndTime);
      }
    },
    selectMaterials() {
      console.log("selectMaterials",this.formData)
      this.$refs["DialogDrillDictionarySelect"].show(this.formData.type);
    },
    drillDictionarySelect(data){
      // console.log("selectMaterials",this.formData)
      if(this.formData.type==null)
      {
        this.formData.type=parseInt(data[0].drillType);
      }
      this.formData.presetCase=data[0].defaultCause;
    },

  },

  mounted() {
  },
};
</script>

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