<template>
  <!-- 文件信息编辑弹窗 -->
  <div class="examination batch-edit-wrap">
    <el-dialog
      @close="closeDialog"
      :visible.sync="templateShowFlag"
      customClass="dialog_wrap"
      :close-on-click-modal="false"
    >
      <div slot="title" class="titleBox">
        <i
          :class="tableType === 0 ? 'el-icon-document' : 'el-icon-edit-outline'"
          style="font-size: 20px"
        ></i>
        <span style="margin-left: 10px; font-size: 18px">{{ type }}</span>
      </div>
      <el-form
        ref="editData"
        label-width="65px"
        :inline="true"
        :model="editData"
        :rules="formRules"
      >
        <el-form-item prop="isoStdNo" label="体系编号">
          <el-input
            v-model="editData.isoStdNo"
            clearable
            size="small"
            style="width: 190px"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item prop="isoTypeName" label="体系类型">
          <el-select
            v-model="editData.isoTypeName"
            filterable
            style="width: 190px"
            collapse-tags
            @change="baseInfoSelected(editData.isoTypeName, 'isoTypeCode')"
            size="small"
          >
            <el-option
              v-for="item in isoTypeList"
              :key="item.baseCode"
              :label="item.baseName"
              :value="item.baseName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="isoName" label="体系名称">
          <el-input
            v-model="editData.isoName"
            clearable
            size="small"
            style="width: 190px"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item prop="isoDesc" label="体系描述">
          <el-input
            v-model="editData.isoDesc"
            clearable
            size="small"
            style="width: 190px"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item prop="companyNo" label="管理单位">
          <el-select
            v-model="editData.companyNo"
            filterable
            style="width: 190px"
            collapse-tags
            @change="selectDepartment"
            size="small"
          >
            <el-option
              v-for="item in unitList"
              :key="item.orgCode"
              :label="item.orgName"
              :value="item.orgCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="startTime" label="生效日期">
          <el-date-picker
            v-model="editData.startTime"
            size="small"
            type="date"
            style="width: 190px"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item prop="deptNo" label="管理科室">
          <el-select
            v-model="editData.deptNo"
            filterable
            style="width: 190px"
            collapse-tags
            @change="selectPlanMent"
            size="small"
          >
            <el-option
              v-for="item in sectionList"
              :key="item.orgCode"
              :label="item.orgName"
              :value="item.orgCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="endTime" label="失效日期">
          <el-date-picker
            v-model="editData.endTime"
            size="small"
            type="date"
            style="width: 190px"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item prop="sectionNo" label="管理班组">
          <el-select
            v-model="editData.sectionNo"
            clearable
            filterable
            style="width: 190px"
            collapse-tags
            @change="selectPlanSection"
            size="small"
          >
            <el-option
              v-for="item in planTeamList"
              :key="item.orgCode"
              :label="item.orgName"
              :value="item.orgCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="memo" label="备注">
          <el-input
            v-model="editData.memo"
            clearable
            size="small"
            style="width: 190px"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="文件上传" prop="filePath">
          <el-input
            v-model="editData.filePath"
            size="small"
            readonly
            disabled
            style="width: 352px; display: inline-block"
          ></el-input>
          <el-upload
            class="upload"
            action=""
            v-if="editData.filePath - 0 === 0"
            style="width: 40px; display: inline-block"
            :multiple="false"
            :show-file-list="false"
            accept=""
            :http-request="httpRequest"
          >
            <el-button
              type="goon"
              size="mini"
              icon="el-icon-upload2"
            ></el-button>
          </el-upload>
          <el-button
            v-else
            type="primary"
            size="mini"
            class="el-icon-circle-close"
            @click="dropFile"
          ></el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="saveData">确定</el-button>
        <el-button size="mini" type="default" @click="closeDialog"
          >取消</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getCookie
} from '@/utils/util.js';
import {
  cookieUserId,
  cookieUserName
} from '@/config/config.js';
let userName = getCookie(cookieUserName);
let userId = getCookie(cookieUserId);
export default {
  props: ['type', 'templateShowFlag', 'baseData'],
  data () {
    return {
      // 编辑的数据对象
      formRules: {
        isoStdNo: [{required: true, message: '该项不能为空', trigger: 'input'}],
        isoTypeName: [{required: true, message: '该项不能为空', trigger: 'input'}],
        isoName: [{required: true, message: '该项不能为空', trigger: 'input'}],
        companyNo: [{required: true, message: '该项不能为空', trigger: 'input'}]
      },
      editData: {
        classNo: '',
        className: '',
        fileTypeNo: '',
        fileTypeName: '',
        fileName: '',
        fileLevel: '',
        startTime: '',
        endTime: '',
        companyNo: '',
        companyName: '',
        fileSource: '',
        deptNo: '',
        deptName: '',
        startDate: '',
        sectionNo: '',
        sectionName: '',
        endDate: '',
        memo: '',
        filePath: ''
      },
      editDataCache: {
        classNo: '',
        className: '',
        fileTypeNo: '',
        fileTypeName: '',
        fileName: '',
        fileLevel: '',
        companyNo: '',
        companyName: '',
        fileSource: '',
        deptNo: '',
        deptName: '',
        startDate: '',
        sectionNo: '',
        sectionName: '',
        endDate: '',
        memo: '',
        filePath: ''
      },
      tableType: 0, // 当前是编辑还是新增， 0为新增
      unitList: [], // 单位
      sectionList: [], // 车间
      planTeamList: [], // 班组
      isoTypeList: []
    }
  },
  async created () {
    this.axios
        .post(
            "pass/baseManagement/v1/limsbaseinfos/queryBaseInfoByBaseCode",
            { validFlag: 1, baseCode: 4853 },
            { individualType: "json" }
        )
        .then((res) => {
            this.isoTypeList = res.data;
        });
    this.editData.startTime = this.getYNM(new Date());
    this.editData.endTime = this.getYNM(new Date());
    this.getUnitData()
  },
  async mounted () {
  },
  methods: {
    getCode (code, arr, codeKey, nameKey) {
      if (!code) {
        return '';
      }
      let targetRow = arr.find(item => {
        return item[codeKey] === code;
      });
      return targetRow ? targetRow[nameKey] : '';
    },
    getYNM (date) {
      let year = date.getFullYear().toString();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      month = month < 10 ? "0" + month : month;
      day = day < 10 ? "0" + day : day;
      return `${year}-${month}-${day}`;
    },
    // 关闭弹窗
    closeDialog () {
      this.$emit('close')
    },
    // 保存数据
    async saveData () {
      // if (this.editData.filePath - 0 === 0) {
      //   return this.$message.warning('请上传文件')
      // }
      this.editData.isoTypeCode = this.getCode(this.editData.isoTypeName,this.isoTypeList,'baseName', 'baseCode')
       this.$refs.editData.validate(async valid => {
        if (valid) {
          const data = await this.axios.post('pass/baseManagement/v1/limsisotmps/insertupdate', { ...this.editData }, { individualType: 'json' })
          if (data.status === 'succeed') {
            this.$message.success('操作成功')
            this.closeDialog()
            this.$emit('refresh')
          } else {
            this.$message.error('操作异常请重试')
          }
        }
      })
    },
    // 获取单位数据
    getUnitData () {
      this.axios
        .post(
          "pass/baseManagement/v1/sysorgs/querySysOrgCompanyAll",
          {},
          { individualType: "json" }
        )
        .then((response) => {
          this.unitList = response.data;
        });
    },
    //查询选中的单位的车间数据
    selectDepartment (val, flag) {
      // 获取编码对应的单位名称
      this.sectionList = [];
      this.unitList.find((item) => {
        if (val === item.orgCode) {
          this.sectionList = item.sysOrgList;
          this.editData.companyName = item.orgName
          if (!flag) {
            this.editData.deptName = ''
            this.editData.deptNo = ''
          }
        }
      });
    },
    // 根据车间联动查询班组数据
    selectPlanMent (val, flag) {
      this.planTeamList = []
      this.sectionList.find((item) => {
        if (val === item.orgCode) {
          this.planTeamList = item.sysOrgList;
          this.editData.deptName = item.orgName
          if (!flag) {
            this.editData.sectionNo = ''
            this.editData.sectionName = ''
          }
        }
      });
    },
    // 查找选中班组对应编码
    selectPlanSection (val) {
      this.planTeamList.find((item) => {
        if (val === item.orgCode) {
          this.editData.sectionName = item.orgName
        }
      });
    },
    // 获取选中文件类别对应编码
    baseInfoSelected (val, valName) {
      if (val) {
        let item = this.fileTypeList.find(item => item.baseName === val)
        if (item) {
          this.editData[valName] = item.baseCode
        }
      } else {
        this.editData[valName] = ''
      }
    },
    // 获取文件相关基础信息
    getBaseInfo () {
      this.axios.post("pass/baseManagement/v1/limsbaseinfos/queryBaseInfoByBaseCode", { validFlag: 1, baseCode: 4801 }, { individualType: 'json' }).then(res => {
        this.fileTypeList = res.data
      })
    },
    // 文件上传
    async httpRequest (e) {
      let _this = this;
      if (!e.file) {
        // 没有文件
        return false
      }
      let file = new FormData()
      file.append('file', e.file)
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      this.axios.post('pass/baseManagement/v1/file/upload', file, config).then(res =>{
        if (res.code === '0' || res.code === '200') {
          this.$message.success('上传成功')
          this.editData.filePath = res.data[0].fileName
        } else {
          this.$message.error(res.message)
        }
      }).catch(e => {
        return this.$message.error(e.message)
      })
    },
    // 删除已有文件
    async dropFile () {
      let result = await this.MessageBox.confirm('确认删除该文件重新上传吗？').catch(() => 'cancel')
      if (result == 'cancel') return
       try {
         const data = await this.axios.post('pass/baseManagement/v1/limsisotmps/delectFile', {stId : this.editData.id}, { individualType: 'json' })
          if (data.status === 'succeed') {
            this.editData.filePath = ''
            this.$message.success('文件删除成功')
          } else {
            this.$message.error(data.message)
          }
      } catch (e) {
        this.$message.error('文件删除失败，请重试')
      }
    }
  },
  watch: {
    async baseData (newVal, oldVal) {
      this.editData = { ...this.editDataCache, ...newVal }
      if(this.editData.startTime == null || this.editData.startTime == ""){
        this.editData.startTime = this.getYNM(new Date());
      }
      if(this.editData.endTime == null || this.editData.endTime == ""){
        this.editData.endTime = this.getYNM(new Date());
      }
      console.log(1)
      if (this.unitList.length === 0) {
        await this.getUnitData()
      }
      console.log(this.unitList)
      if (this.editData.companyNo - 0 !== 0) {
        this.selectDepartment(this.editData.companyNo, true)
      }
      console.log(this.editData)
      if (this.editData.deptNo - 0 !== 0) {
        this.selectPlanMent(this.editData.deptNo, true)
      }
    }
  }
}
</script>
<style>
.batch-edit-wrap .el-icon-close {
  display: none;
}

.batch-edit-wrap .el-dialog__header {
  padding-top: 0px;
}

.batch-edit-wrap .el-select .el-input__inner {
  padding-right: 25px !important;
}

.dialog_wrap {
  width: 600px !important;
}

.dialog_wrap .el-dialog__footer {
  text-align: center;
}
</style>
