<template>
  <!-- 文件信息编辑弹窗 -->
  <div class="examination batch-edit-wrap">
    <el-dialog
      @close="closeDialog"
      :visible.sync="fileShowFlag"
      customClass="dialog_wrap"
    >
      <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"
      >
        <el-form-item prop="className" label="文件分类">
          <el-input
            v-model="editData.className"
            clearable
            size="small"
            style="width: 160px"
            disabled
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item prop="fileTypeName" label="文件类别">
          <el-select
            v-model="editData.fileTypeName"
            filterable
            style="width: 160px"
            collapse-tags
            @change="baseInfoSelected(editData.fileTypeName, 'fileTypeNo')"
            size="small"
          >
            <el-option
              v-for="item in fileTypeList"
              :key="item.baseCode"
              :label="item.baseName"
              :value="item.baseName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="fileName" label="文件名称">
          <el-input
            v-model="editData.fileName"
            clearable
            size="small"
            style="width: 160px"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item prop="fileLevel" label="文件级别">
          <el-select
            v-model="editData.fileLevel"
            filterable
            style="width: 160px"
            collapse-tags
            size="small"
          >
            <el-option
              v-for="item in fileLevelList"
              :key="item.baseCode"
              :label="item.baseName"
              :value="item.baseName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="companyNo" label="管理单位">
          <el-select
            v-model="editData.companyNo"
            filterable
            style="width: 160px"
            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="fileSource" label="文件来源">
          <el-select
            v-model="editData.fileSource"
            filterable
            style="width: 160px"
            collapse-tags
            size="small"
          >
            <el-option
              v-for="item in fileSourceList"
              :key="item.baseCode"
              :label="item.baseName"
              :value="item.baseName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="deptNo" label="管理车间">
          <el-select
            v-model="editData.deptNo"
            filterable
            style="width: 160px"
            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="startDate" label="生效日期">
          <el-date-picker
            v-model="editData.startDate"
            size="small"
            type="date"
            style="width: 160px"
            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: 160px"
            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="endDate" label="失效日期">
          <el-date-picker
            v-model="editData.endDate"
            size="small"
            type="date"
            style="width: 160px"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item prop="memo" label="备注">
          <el-input
            v-model="editData.memo"
            clearable
            size="small"
            style="width: 392px"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="文件上传">
          <el-input
            v-model="editData.filePath01"
            size="small"
            readonly
            disabled
            style="width: 352px; display: inline-block"
          ></el-input>
          <el-upload
            v-if="editData.filePath01 - 0 === 0"
            class="upload"
            action=""
            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', 'fileShowFlag', 'baseData'],
  data () {
    return {
      // 编辑的数据对象
      editData: {
        classNo: '',
        className: '',
        fileTypeNo: '',
        fileTypeName: '',
        fileName: '',
        fileLevel: '',
        companyNo: '',
        companyName: '',
        fileSource: '',
        deptNo: '',
        deptName: '',
        startDate: '',
        sectionNo: '',
        sectionName: '',
        endDate: '',
        memo: '',
        savePath: '',
        filePath01: ''
      },
      editDataCache: {
        classNo: '',
        className: '',
        fileTypeNo: '',
        fileTypeName: '',
        fileName: '',
        fileLevel: '',
        companyNo: '',
        companyName: '',
        fileSource: '',
        deptNo: '',
        deptName: '',
        startDate: '',
        sectionNo: '',
        sectionName: '',
        endDate: '',
        memo: '',
        savePath: '',
        filePath01: ''
      },
      tableType: 0, // 当前是编辑还是新增， 0为新增
      unitList: [], // 单位
      sectionList: [], // 车间
      planTeamList: [], // 班组
      fileTypeList: [], // 文件类别
      fileLevelList: [], // 文件级别
      fileSourceList: [] // 文件来源
    }
  },
  async created () {
  },
  async mounted () {
    this.getUnitData();
    this.getTypeData();
    this.getLevelData();
    this.getSourceData();
  },
  methods: {
    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')
    },
    closeDialog1 () {
      this.$emit('refresh')
    },
    // 保存数据
    async saveData () {
      // if (this.editData.filePath01 - 0 === 0) {
      //   return this.$message.warning('请上传文件')
      // }
      this.editData.tenantNo = '2'
      const data = await this.axios.post('pass/baseManagement/v1/limsisofiles/insertupdate', { ...this.editData }, { individualType: 'json' })
      if (data.status === 'succeed') {
        this.$message.success('操作成功')
        this.closeDialog1()
      } else {
        this.$message.error(data.message)
      }
    },
    // 获取单位数据
    getUnitData () {
      this.axios
        .post(
          "pass/baseManagement/v1/sysorgs/querySysOrgCompanyAll",
          {},
          { individualType: "json" }
        )
        .then((response) => {
          this.unitList = response.data;
        });
    },
    // 获取文件类别数据
    getTypeData () {
      this.axios
        .get(
          "pass/baseManagement/v1/limsbaseinfos/like/?pageNum=1&pageSize=50&baseCode=4809",
          {},
          { individualType: "json" }
        )
        .then((response) => {
          if (response.data && response.data.list.length > 0) {
            this.fileTypeList = response.data.list.filter(item => item.baseCode != '4809');
          }
        });
    },
    // 获取文件级别数据
    getLevelData () {
      this.axios
        .get(
          "pass/baseManagement/v1/limsbaseinfos/like/?pageNum=1&pageSize=50&baseCode=4839",
          {},
          { individualType: "json" }
        )
        .then((response) => {
          if (response.data && response.data.list.length > 0) {
            this.fileLevelList = response.data.list.filter(item => item.baseCode != '4839');
          }
        });
    },
    // 获取文件来源数据
    getSourceData () {
      this.axios
        .get(
          "pass/baseManagement/v1/limsbaseinfos/like/?pageNum=1&pageSize=50&baseCode=4844",
          {},
          { individualType: "json" }
        )
        .then((response) => {
          if (response.data && response.data.list.length > 0) {
            this.fileSourceList = response.data.list.filter(item => item.baseCode != '4844');
          }
        });
    },
    //查询选中的单位的车间数据
    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] = ''
      }
    },
    // 删除已有文件
    async dropFile () {
      let result = await this.MessageBox.confirm('确认删除该文件重新上传吗？').catch(() => 'cancel')
      if (result == 'cancel') return
      try {
         const data = await this.axios.post('pass/baseManagement/v1/limsisofiles/delectFile', {stId : this.editData.id}, { individualType: 'json' })
          if (data.status === 'succeed') {
            this.editData.filePath01 = ''
            this.$message.success('文件删除成功')
          } else {
            this.$message.error(data.message)
          }
      } catch (e) {
        this.$message.error('文件删除失败，请重试')
        console.log(e)
      }
    },
    // 文件上传
    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.fileName = res.data[0].oldFileName
          this.editData.filePath01 = res.data[0].fileName
        } else {
          this.$message.error(res.message)
        }
      }).catch(e => {
        return this.$message.error(e.message)
      })
      // // 先获取文件id
      // const data = await this.axios.get('/icore.icp.web/file')
      // if (data.status - 0 !== 200 || data.data.url - 0 === 0) {
      //   return this.$message.error('操作异常，请重试')
      // }
      // let fileId = data.data.fid
      // let uploadPath = data.data.url.split('.')[0]
      // let uploadFile = new FormData()
      // uploadFile.append('file', file)
      // let config = {
      //   headers: {
      //     'Content-Type': 'multipart/form-data'
      //   }
      // }
      // 上传文件
      // const fileData = await this.axios.post(`/icore.icp.web/${uploadPath}/${fileId}`, uploadFile, config)
      // console.log(fileData, '文件上传结果')
      // if (fileData.status - 0 === 201 && fileData.data.size - 0 > 0) {
      //   this.$message.success('上传成功')
      //   this.editData.fileName = fileData.data.name
      //   this.editData.filePath01 = `/${uploadPath}/${fileId}`
      // } else {
      //   return this.$message.error('操作异常，请重试')
      // }
    },
  },
  watch: {
    async baseData (newVal, oldVal) {
      this.editData = { ...this.editDataCache, ...newVal }
      if(this.editData.startDate == null || this.editData.startDate == ""){
        this.editData.startDate = this.getYNM(new Date())
      }
      if(this.editData.endDate == null || this.editData.endDate == ""){
        this.editData.endDate = this.getYNM(new Date())
      }
      if (this.unitList.length === 0) {
        await this.getUnitData()
      }
      if (this.editData.companyNo - 0 !== 0) {
        this.selectDepartment(this.editData.companyNo, true)
      }
      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: 520px !important;
}

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