<template>
  <div class="edu-training-edit">
    <DialogCom
      :title="title"
      @close="onHide"
      :visible.sync="isShow"
      width="1000px"
    >
      <div class="page-body">
        <el-form
          ref="form"
          :model="formData"
          :rules="formDataRules"
          label-width="140px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="介绍信编号" prop="letterNo">
                <el-input
                  v-model="formData.letterNo"
                  placeholder="请输入介绍信编号"
                  maxlength="10"
                />
              </el-form-item>
            </el-col>            
            <el-col :span="12">
              <el-form-item label="接待机构" prop="receptionOrgIds">
                <org-tree-select v-model="formData.receptionOrgIds" ref="orgTreeSelect">
                </org-tree-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="reasons" label="来访事由">
                <el-input
                  v-model="formData.reasons"
                  placeholder="请输入来访事由"
                  maxlength="100"
                />
              </el-form-item>
            </el-col>            
            <el-col :span="12">
              <el-form-item prop="startTime" label="开具日期">
                <!-- <el-date-picker
                  v-model="formData.range"
                  type="daterange"
                  :picker-options="startDatepickerOptions"
                  range-separator="至"
                  start-placeholder="有效期开始日期"
                  end-placeholder="有效期结束日期">
                </el-date-picker> -->
                <el-date-picker style="width:100%"
                  v-model="formData.startTime"
                  type="date"
                  :picker-options="startDatepickerOptions"
                  placeholder="请选择开具日期"
                  >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="effectiveDays" label="有效天数">
                <el-input-number style="width: 100%" v-model="formData.effectiveDays" :min="1" :max="365"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上传介绍信附件" prop="letterFile">
                <K-file-upload
                  ref="upload"
                  :limit=2
                  :defaultValue="formFileListDefualtValue"
                  v-model="formData.letterFile"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="description">
                <el-input
                  v-model="formData.description"
                  placeholder="请输入备注"
                  maxlength="100"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="10">
            <el-col :span="12">
                <h3>
                  <i class="el-icon-collection-tag"></i>
                  人员信息
                </h3> 
            </el-col>
            <el-col :offset="8" :span="2">
              <h3>
                <el-button
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="handleAddUser"
                >新增来访人员</el-button
              >
                </h3> 
             
            </el-col>
          </el-row>

          <el-table border :data="formData.userInfos" max-height="500" style="margin-bottom: 10px;">
            <el-table-column label="序号"  align="center"  type="index" width="70" />
            <el-table-column label="来访单位" width="100" align="center" prop="companyName" />
            <el-table-column label="来访人员" width="100" align="center" prop="userName" />
            <el-table-column label="证件类型" width="100" align="center" prop="idType">
              <template slot-scope="scope">
              <dict-tag :options="dict.type.letter_id_type" :value="scope.row.idType"/>
            </template>
            </el-table-column>
            <el-table-column label="证件号码" width="200" align="center" prop="idCard">
            </el-table-column>
            <el-table-column label="证件图片" align="center" prop="imgFile">
              <template slot-scope="scope">                      
                      <ImageListPreview v-model="scope.row.imgFile"></ImageListPreview>                  
                    </template> 
               </el-table-column>
            <el-table-column
              label="操作"
              align="center" width="100"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="editUser(scope.row)"
                  >编辑</el-button
                >
                <el-button size="mini" type="text" @click="remove(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>

      <DialogCom
        title="添加来访人员"
        :visible.sync="open"
        width="600px"
        append-to-body
        @close="onHideUser"
      >
        <el-form
          ref="formUser"
          :model="userInfo"
          :rules="userInfoRules"
          label-width="120px"
        >  
          <el-form-item label="来访单位" prop="companyName">
            <el-input v-model="userInfo.companyName" maxlength="20" placeholder="请输入来访单位" />
          </el-form-item>
          <el-form-item label="来访人员" prop="userName">
            <el-input v-model="userInfo.userName" maxlength="10" placeholder="请输入来访人员" />
          </el-form-item>
          <el-form-item label="证件类型" prop="idType">
            <el-select style="width:100%" v-model="userInfo.idType" placeholder="请选择证件类型" clearable>
            <el-option
              v-for="dict in dict.type.letter_id_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            />
        </el-select>
          </el-form-item>
          <el-form-item label="证件号码" prop="idCard">
            <el-input v-model="userInfo.idCard" maxlength="20" placeholder="请输入证件号码" />
          </el-form-item>
          <el-form-item prop="imgFile" label="上传证件图片">
            <!-- <ImageListPreview v-model="userInfo.imgFile"></ImageListPreview> -->
            <imgUpload ref="uploadimage" type="more" :value="userInfo.imgFile" :limit=2
                           @input="imageListChanged"></imgUpload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitUser">确 定</el-button>
          <el-button @click="onHideUser">取 消</el-button>
        </div>
      </DialogCom>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="onHide">取 消</el-button>
      </div>
    </DialogCom>
  </div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
import {
  listLetter,
  getLetter,
  delLetter,
  addLetter,
  updateLetter,
} from "@/api/core/letter";
import OrgTreeSelect from "@/components/orgTreeSelect";
import KFileUpload from "@/components/K-FileUpload/index.vue";
import dayjs from "dayjs";
import imgUpload from "@/components/ImageUpload";
import DataRangePicker from "@/components/dateTime/daterange.picker.vue";
export default {
  components: { OrgTreeSelect, KFileUpload, imgUpload,DataRangePicker },
  data() {
    const params = this.$route.params;
    return {
      id: params ? params.id : null,
      isShow: false,
      title: "录入介绍信",
      formData: this.reset(),
      formDataRules: {
        reasons: [{ required: true, message: "请输入来访事由" }],
        letterNo: [{ required: true, message: "请输入介绍信编号" }],
        receptionOrgIds: [{ required: true, message: "请选择接待机构" }],
        startTime: [{ required: true, message: "请选择开具日期" }],      
        effectiveDays: [{ required: true, message: "请选择有效天数" }],   
        userInfos: [{ required: true, message: "请添加来访人员" }],
        letterFile:[{ required: true, message: "请上传介绍信附件" }],
      },
      userInfoRules: {
        userName: [{ required: true, message: "请输入来访人员" }],
        companyName: [{ required: true, message: "请输入来访单位" }],
        idType: [{ required: true, message: "请选择证件类型" }],
        idCard: [{ required: true, message: "请输入证件号码" }],
        imgFile: [{ required: true, message: "请上传证件图片" }],
      },
      startDatepickerOptions: {
        disabledDate: this.endDisabledDate,
      },
      // endDatepickerOptions: {
      //   disabledDate: this.endDisabledDate,
      // },
      formFileListDefualtValue: [],
      open: false,
      userInfo: this.resetUserInfo(),
      imageList: [],
    };
  },
  dicts: ["letter_status","letter_id_type"],
  props: {},
  watch: {},
  created() {},
  computed: {
    ...mapState(["loginUser", "org"]),
  },
  methods: {
    ...mapMutations([]),
    reset(other = {}) {
      return {
        reasons: null,
        letterNo:null,
        receptionOrgIds: [],
        // range:[],
        startTime:new Date(),
        effectiveDays:1,
        description: null,
        letterFile: [],
        userInfos: [],
        type:1,
        status:0,
        ...other,
      };
    },
    resetUserInfo() {
      return {
        userName: null,
        companyName: null,
        idType:0,
        idCard: null,
        imgFile: null,
      };
    },

    async show(id, other = {}) {     
      if (id) {
        this.title = "编辑介绍信";   
        this.isShow = true;
        getLetter(id).then((response) => {
          // let tempRange=[];
          // tempRange.push(dayjs(response.data.startTime));
          // tempRange.push(new Date(response.data.endTime));
          // response.data.range=tempRange;
          this.formData = response.data;
          this.formFileListDefualtValue=this.formData.letterFile;
        });        
      }
      else 
      {
        this.isShow = true;
        this.title = "录入介绍信";
        this.formData = this.reset();       
      }
    },
    handleAddUser() {
      this.open = true;
    },
    imageListChanged(list) {
      this.userInfo.imgFile = list;
    },
    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) {
      if (
        dayjs(this.formData.startTime).isAfter(dayjs(this.formData.endTime))
      ) {
        this.formData.endTime = this.formData.startTime;
      }
    },
    endDateChanged(time) {
      if (
        dayjs(this.formData.startTime).isAfter(dayjs(this.formData.endTime))
      ) {
        this.formData.startTime = this.formData.endTime;
      }
    },
    onHide() {
      this.isShow = false;
      this.formData = this.reset();
      this.$refs["upload"].clearFiles();
    },
    onHideUser() {
      this.open = false;
      this.imageList = [];
      this.userInfo = this.resetUserInfo();
    },
    submitUser() {
      this.$refs["formUser"].validate((valid) => {
        if (valid) {
          this.open = false;
          console.log("================", this.userInfo);
          let userIndex = this.formData.userInfos.findIndex(x=>x.idCard==this.userInfo.idCard);
          if(userIndex>-1)
          {
            this.formData.userInfos.splice(userIndex, 1);
          }
          this.formData.userInfos.push(this.userInfo);
          this.userInfo = this.resetUserInfo();
          this.imageList = [];
        }
      });
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.formData.userInfos.length <= 0) {
            this.$message.error("请添加人员");
            return;
          }
          console.log("================", this.formData);
          if (this.formData.id != null) {
            updateLetter(this.formData).then((response) => {
              this.$modal.msgSuccess("编辑成功");
              this.isShow = false;
              this.formData = this.reset();
              this.$emit("success", this.formData);
            });
          } else {
            addLetter(this.formData).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.isShow = false;
              this.formData = this.reset();
              this.$emit("success", this.formData);
            });
          }
        }
      });
    },
    editUser(row) {
      this.open = true;
      this.userInfo = row;
    },
    remove(row) {
      console.log("================", row);
      this.formData.userInfos.splice(this.formData.userInfos.indexOf(row), 1);
    },
  },
  mounted() {},
};
</script>




