<template>
  <div class="edu-training-edit">
    <el-dialog :title="'培训登记'" :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="12">
              <el-form-item prop="title" label="培训主题">
                <!-- <el-input
                        v-model="formData.title"
                        :maxlength="32"
                        placeholder="请输入培训主题"
                        clearable
                        readonly
                        disabled
                    /> -->
                {{ formData.title }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="orgName" label="培训机构">
                {{ formData.orgName }}
              </el-form-item>
            </el-col>
            <!-- 类型 -->
            <el-col :span="24">
              <el-form-item prop="type" label="类型">
                <el-select v-model="formData.type" placeholder="请选择执行机构类型" clearable>
                  <el-option v-for="dict in dict.type.edu_type" :key="dict.value" :label="dict.label"
                    :value="parseInt(dict.value)" />
                </el-select>
                <!-- <k-select-constant
                        name="EduTrainingType"
                        v-model="formData.type"
                        placeholder="请选择类型"
                    ></k-select-constant> -->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item v-if="formData.id" prop="dateTime" label="培训开始时间">
                <el-date-picker v-model="formData.trainingStartDateTime" type="datetime" placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item v-if="formData.id" prop="dateTime" label="培训结束时间">
                <el-date-picker v-model="formData.trainingEndDateTime" type="datetime" placeholder="选择日期">
                </el-date-picker>
              </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 v-if="formData.id" prop="hostId" label="主持人">
                <k-select
                  v-model="formData.hostId"
                  url="/user/find/all"
                  :params="{ orgId: formData.orgId }"
                  placeholder="请选择主持人"
                ></k-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item v-if="formData.id" prop="recorderId" label="记录人">
                <k-select
                  v-model="formData.recorderId"
                  url="/user/find/all"
                  :params="{ orgId: formData.orgId }"
                  placeholder="请选择记录人"
                ></k-select>
              </el-form-item>
            </el-col> -->
            <!-- 截止日期 -->
            <!-- <el-col :span="24">
              <el-form-item v-if="formData.id" prop="dateTime" label="培训时间">
                <el-date-picker
                  v-model="formData.dateTime"
                  type="datetime"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col> -->
            <!-- 总结 -->
            <el-col :span="24">
              <el-form-item v-if="formData.id" prop="note" label="总结">
                <k-textarea v-model="formData.note" placeholder="请输入总结" :length="1000" />
              </el-form-item>
            </el-col>
            <!-- 应到人数 -->
            <!-- <el-col :span="24">
              <el-form-item v-if="formData.id" prop="dueCount" label="应到人数">
                <el-input-number
                  v-model="formData.dueCount"
                  :min="0"
                  placeholder="请输入应到人数"
                ></el-input-number>
              </el-form-item>
            </el-col> -->
            <!-- 实到人数 -->
            <!-- <el-col :span="24">
              <el-form-item
                v-if="formData.id"
                prop="actualCount"
                label="实到人数"
              >
                <el-input-number
                  v-model="formData.actualCount"
                  :min="0"
                  placeholder="请输入实到人数"
                ></el-input-number>
              </el-form-item>
            </el-col> -->
            <el-col :span="24">
              <el-form-item v-if="formData.id" label="参与人员">
                <k-select :multiple="true" v-model="formData.absenceList" url="/user/find/all"
                  :params="{ orgId: formData.orgId }" placeholder="请选择缺席人员" @select="absenceUserSelectChanged"></k-select>
                <!-- <k-select :multiple="true" v-model="formData.absenceList" url="/user/find/all"
                  :params="{ orgId: formData.orgId }" placeholder="请选择参与人员"></k-select> -->
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item v-if="formData.id" 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 type="more" :value="formData.imageList" @input="imageListChanged"></imgUpload>
                <!-- <k-multi-upload v-model="formData.imageList" limit="4" byModule moduleName="edu-training" /> -->
              </el-form-item>
            </el-col>
            <!-- 上传文件 -->
            <!-- <el-col :span="24">
              <el-form-item prop="fileList" label="上传文件">
                <k-upload-file-multiple :disabled="!!id" v-model="formData.fileList" max="4"
                  @uploadTriggerEvent="uploadTriggerEvent" byModule
                  moduleName="edu-traning-perform"></k-upload-file-multiple>
              </el-form-item>
            </el-col> -->
          </el-row>
        </el-form>
      </div>

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

<script>
import { mapState, mapMutations } from "vuex";
import { getEduTask, recordEduTask } from "@/api/core/edu/eduTask";
import KTextarea from "@/components/common/textarea.vue";
import KSelect from "@/components/common/userselect.vue";
import imgUpload from "@/components/ImageUpload/index.vue";
export default {
  components: { KTextarea, KSelect, imgUpload },
  data() {
    const params = this.$route.params;
    return {
      id: params ? params.id : null,
      isShow: false,
      formData: this.reset(),
      formDataRules: {
        type: [{ required: true, message: "请选择类型" }],
        content: [{ required: true, message: "请输入内容" }],
        // hostId: [{ required: true, message: "请输入主持人" }],
        // recorderId: [{ required: true, message: "请输入记录人" }],

        trainingStartDateTime: [{ required: true, message: "请输入培训时间" }],
        trainingEndDateTime: [{ required: true, message: "请输入培训时间" }],
        note: [{ required: true, message: "请输入总结" }],
        // dueCount: [{ required: true, message: "请输入应到人数" }],
        // actualCount: [{ required: true, message: "请输入实到人数" }],
      },
    };
  },
  dicts: ['edu_type', 'edu_task_status'],
  props: {},
  watch: {},
  computed: {
    ...mapState(["loginUser", "org"]),
  },
  methods: {
    ...mapMutations([]),
    reset(other = {}) {
      return {
        // hostId: null,
        // recorderId: null,
        trainingStartDateTime: null,
        trainingEndDateTime: null,
        // dueCount: null,
        // actualCount: 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;
      }
      getEduTask(id).then(response => {
        this.formData = response.data;
        this.loading = false;
        if (this.formData.imageList == null) {
          this.formData.imageList = [];
        }
        if (this.formData.fileList == null) {
          this.formData.fileList = [];
        }
        if (this.formData.taskUserList) {
          let list1 = this.formData.taskUserList.filter((element) => 
            element.type === 1
          );
          console.log("list1",list1)
          this.formData.absenceList = list1 ? list1.map((a) =>{ return a.userId;})
            : [];

          let list2 = this.formData.taskUserList.filter((element) => 
            element.type === 2
          );
          console.log("list2",list2)
          this.formData.absentList = list2 ? list2.map((a) =>{ return a.userId;})
            : [];
        }
        else {
          this.formData.absenceList = [];
          this.formData.absentList = [];
        }
      })
      console.log("getEduTask",this.formData);
    },
    async show(id, other = {}) {
      this.id = id;
      await this.refresh(id, other);
      this.isShow = true;
    },
    imageListChanged(list) {
      this.formData.imageList = list;
      console.log("imageListChanged", this.formData.imageList);
    },
    absentUserSelectChanged(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);
    },
    // 事件
    onHide() {
      this.isShow = false;
      this.formData=this.reset();
    },
    async onSave(){
      if (!this.validatePerson()) {
        this.$message.error("参与人员与缺席人员重复，请重新选择!");
        return;
      }
      let request ={submitType:1,...this.formData};
      recordEduTask(request).then((v) => {
          this.$emit("success", this.formData);
          this.onHide();
        });
    },
    async onSubmit() {
      await this.$refs.form.validate();
      console.log("onSubmit this.formData", this.formData)
      let due = this.formData.dueCount;
      let actual = this.formData.actualCount;
      if (actual > due) {
        this.$message.error("实到人数不能大于应到人数!");
      } else if (!this.validatePerson()) {
        this.$message.error("参与人员与缺席人员重复，请重新选择!");
      } else {
        let request ={submitType:2,...this.formData};
        recordEduTask(request).then((v) => {
          this.$emit("success", this.formData);
          this.onHide();
        });
        // 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) { },
    // 事件
    //apimark//
  },
  mounted() { },
};
</script>

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