<template>
    <div class="examination">
     <el-dialog @close="closeDialog" :visible.sync="dialogTableVisible" customClass="customWidth_stan">
        <div slot="title" class="titleBox">
         <i :class="tableType === 0? 'el-icon-document':'el-icon-edit-outline'" style="font-size: 20px"></i>
        <!-- <img style="width: 25px; height: 25px" src='../../../../assets/img/imgScreen/more.png' /> -->
        <span style="margin-left:10px;font-size:18px">{{tableTypeDsc}}</span>
        </div>
        <el-form :model="formData" label-width="80px" :rules="monitorForm.monitorRules" ref="monitorForm" >
         <table class="common-table-style4">
           <tr>
             <td>
               <el-form-item prop="stdNo" label="标准号">
               <el-input v-model="formData.stdNo" size="small" readonly disabled ></el-input>
               </el-form-item>
             </td>
             <td>
               <el-form-item prop="beginTime" label="开始时间">
               <el-date-picker v-model="formData.beginTime" size="small" type="date"  placeholder="选择日期"></el-date-picker>
               </el-form-item>
             </td>
           </tr>
           <tr>
             <td>
               <el-form-item prop="stdName" label="标准名称">
               <el-input v-model="formData.stdName" size="small"  placeholder="请输入"></el-input>
               </el-form-item>
             </td>
             <td>
               <el-form-item prop="closeTime" label="结束时间">
               <el-date-picker v-model="formData.closeTime" size="small" type="date" placeholder="选择日期" ></el-date-picker>
               </el-form-item>
             </td>
           </tr>
           <tr>
             <td>
               <el-form-item prop="stdDesc" label="标准描述">
               <el-input v-model="formData.stdDesc" size="small"  placeholder="请输入"></el-input>
               </el-form-item>
             </td>
             <td>
               <el-form-item prop="companyNo" label="公司名称">
              <el-select v-model="formData.companyNo" filterable style="width:100%" collapse-tags @change="selectDepartment" size="small">
                <el-option v-for="item in companyNameType" :key="item.orgCode" :label="item.orgName" :value="item.orgCode">
                </el-option>
              </el-select>
            </el-form-item>
             </td>
           </tr>
            <tr>
             <td>
               <el-form-item prop="stdVer" label="标准版本号">
               <el-input v-model="formData.stdVer" size="small"  placeholder="请输入"></el-input>
               </el-form-item>
             </td>
             <td>
               <el-form-item prop="sectionName" label="部门名称">
             <el-select v-model="formData.deptNo" filterable style="width:100%" @change="selectClass" collapse-tags size="small" >
                <el-option v-for="item in sectionNameType" :key="item.orgCode" :label="item.orgName" :value="item.orgCode">
                </el-option>
              </el-select>
            </el-form-item>
             </td>
           </tr>
           <tr>
             <td>
               <el-form-item prop='stdTypeCode' label="标准类型">
               <el-select v-model="formData.stdTypeCode" filterable collapse-tags size="small" >
                  <el-option v-for="item in stdTypeNameType" :key="item.baseCode" :label="item.baseName"
                    :value="item.baseCode">
                  </el-option>
                </el-select>
               </el-form-item>
             </td>
             <td>
               <el-form-item prop="deptName" label="班组名称">
             <el-select v-model="formData.sectionNo" style="width:100%" filterable collapse-tags size="small">
                <el-option v-for="item in sectionClass" :key="item.orgCode" :label="item.orgName" :value="item.orgCode">
                </el-option>
              </el-select>
            </el-form-item>
             </td>
           </tr>
           <tr>
             <td>
               <el-form-item prop='stdUsedCode' label="标准用途">
               <el-select v-model="formData.stdUsedCode" filterable collapse-tags size="small" >
                  <el-option v-for="item in stdUsedNameType" :key="item.baseCode" :label="item.baseName"
                    :value="item.baseCode">
                  </el-option>
                </el-select>
               </el-form-item>
             </td>
             <td rowspan="2">
               <el-form-item prop="textarea" label="备注">
               <el-input  type="textarea" :rows="4" v-model="formData.memo" size="small" placeholder="请输入" ></el-input>
               </el-form-item>
             </td>
           </tr>
            <tr>
             <td>
               <el-form-item prop="stdAss" label="标准协会">
               <el-input v-model="formData.stdAss" size="small"  placeholder="请输入"></el-input>
               </el-form-item>
             </td>
            </tr>
           <tr>
             <td colspan="3" style="text-align: left">
               <el-form-item prop="savePath" label="标准文件">
               <el-input v-model="formData.savePath" size="small" readonly disabled style="width: 320px; float:left; margin-right: 5px"></el-input>
               <el-upload
                class="upload"
                action=""
                :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-form-item>
             </td>
           </tr>
         </table>
       </el-form>
       <span slot="footer" class="dialog-footer">
        <el-button type="goon" icon="el-icon-check" size="mini" @click="tableType === 0 ? addData():modifyData()">确定</el-button>
        <el-button size="mini" type="goon" icon="el-icon-remove-outline" @click="cancel">取消</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: ['showFlag', 'Params'],
  data () {
    var closeTimeVerify = (rule, value, callback) => {
        if(this.formData.closeTime){
        //   console.log(Date.parse(this.formData.closeTime),Date.parse(this.formData.beginTime))
        //    console.log(Number(this.formData.closeTime),Number(this.formData.beginTime))
        //  if (Number(this.formData.beginTime) === NaN || Number(this.formData.beginTime) === NaN) {
            if(Date.parse(this.formData.closeTime) > Date.parse(this.formData.beginTime)){
            callback();
            }else{
            callback(new Error('结束时间不得早于开始时间！'));
            }
          // } else {
          //   if(Number(this.formData.closeTime) > Number(this.formData.beginTime)){
          //   callback();
          //   }else{
          //   callback(new Error('结束时间不得早于开始时间！'));
          //   }
          // }
        }else{
          callback();
        }
      };
      return {
          dialogTableVisible: false,
          tableTypeDsc: '新增标准项目',
          tableType: 0,
          seen: true,
          seenNo: true,
          beInvalid: false,
          stdNo: '',
          //beginTime: '',
          //stdName: '',
          //closeTime: '',
          stdDesc: '',
          stdVer: '',
          memo: '',
          stdAss: '',
          savePath: '',
          formData: {
            beginTime: '',
            closeTime: '',
          },
          sectionClass:[],
          companyNameTypeIndex: 0,//公司名称
          deptNameTypeIndex: 0,//部门名称
          stdTypeNameTypeIndex: 0,//标准类型
          stdUsedNameTypeIndex: 0,//标准用途
          sectionNameTypeIndex: 0,//科室名称
          companyNameType: [],
          deptNameType: [],
          stdTypeNameType: [],
          stdUsedNameType: [],
          sectionNameType: [],
          monitorForm: {
          tableData: [{}],
            monitorRules: {
            beginTime: [{ required: true, message: '该项不能为空', trigger: ['blur', 'change'] }],
            closeTime: [{ required: true, message: '该项不能为空', trigger: ['blur', 'change'] },{ required: true, validator: closeTimeVerify, trigger: 'blur' }],
            stdName: [{ required: true, message: '该项不能为空', trigger: 'blur' }],
            stdTypeCode: [{ required: true, message: '该项不能为空', trigger:'change' }],
            companyNo: [{ required: true, message: '该项不能为空', trigger: 'change' }],
            stdUsedCode: [{ required: true, message: '该项不能为空', trigger: 'change' }],
            }
          }
      }
  },
  mounted () {
    //获取公司
    this.axios.post("pass/baseManagement/v1/sysorgs/querySysOrgCompanyAll",{}, {individualType: 'json'}).then(response => {
      this.companyNameType = response.data
    });
    // this.getcompanyNameTypeList ()
    // this.getdeptNameType ()
    this.getstdTypeNameType ()
    this.getstdUsedNameType ()
    // this.getsectionNameType ()
  },
  methods: {
    cancel () {
      this.formData = {}
      this.tableType = 0;
      this.tableTypeDsc = '新增标准项目';
      this.dialogTableVisible = false
    },
    getstdTypeNameType () {
      this.axios.post("pass/baseManagement/v1/limsbaseinfos/queryBaseInfoByBaseCode",{validFlag:1,baseCode:4806}, {individualType: 'json'}).then(res => {
            this.stdTypeNameType = res.data
          })
    },
    getstdUsedNameType () {
      this.axios.post("pass/baseManagement/v1/limsbaseinfos/queryBaseInfoByBaseCode",{validFlag:1,baseCode:4805}, {individualType: 'json'}).then(res => {
            this.stdUsedNameType = res.data
          })
    },
    addData () {
      let _this = this;
      _this.$refs['monitorForm'].validate((valid) => {
        if (valid) {
          this.formData.createMan = userName
          this.formData.createNo = userId
          this.formData.companyName = this.getCode(this.formData.companyNo,this.companyNameType,'orgCode','orgName')
          this.formData.deptName = this.getCode(this.formData.deptNo,this.sectionNameType,'orgCode','orgName')
          this.formData.sectionName = this.getCode(this.formData.sectionNo,this.sectionClass,'orgCode','orgName')
          this.formData.stdTypeName = this.getCode(this.formData.stdTypeCode,this.stdTypeNameType,'baseCode','baseName')
          this.formData.stdUsedName = this.getCode(this.formData.stdUsedCode,this.stdUsedNameType,'baseCode','baseName')
          _this.axios.post('pass/baseManagement/v1/limsstdinfos/saveLimsStdInfo', this.formData, {individualType: 'json'}).then(res => {
            if (res.succeed) {
              _this.dialogTableVisible = false;
              this.$message.success('添加成功')
              _this.$emit('refresh')
            } else {
              this.$message.error(res.message)
            }
          }).catch(e => {
            this.$message.error(e.message)
          })
        }
      })
    },
    //根据选中的公司，查询部门名称数据
    selectDepartment(val){
      this.sectionNameType = []
      this.companyNameType.find(item =>{
        if(val === item.orgCode){
          this.sectionNameType = item.sysOrgList
        }
      })
    },
    //根据选中的部门名称，查询班组名称
    selectClass(val){
      this.sectionClass = []
      this.sectionNameType.find(item =>{
        if(val === item.orgCode){
          this.sectionClass = item.sysOrgList
        }
      })
    },
    getCode (code, arr, codeKey, nameKey) {
      if (!code) {
        return '';
      }
      let targetRow = arr.find(item => {
        return item[codeKey] === code;
      });
      // console.log(targetRow, 'targetRow');
      return targetRow ? targetRow[nameKey] : '';
    },
    modifyData () {
      let _this = this;
      _this.$refs['monitorForm'].validate((valid) => {
        if (valid) {
          this.formData.companyName = this.getCode(this.formData.companyNo,this.companyNameType,'orgCode','orgName')
          this.formData.deptName = this.getCode(this.formData.deptNo,this.sectionNameType,'orgCode','orgName')
          this.formData.sectionName = this.getCode(this.formData.sectionNo,this.sectionClass,'orgCode','orgName')
          this.formData.stdTypeName = this.getCode(this.formData.stdTypeCode,this.stdTypeNameType,'baseCode','baseName')
          this.formData.stdUsedName = this.getCode(this.formData.stdUsedCode,this.stdUsedNameType,'baseCode','baseName')
          _this.axios.post('pass/baseManagement/v1/limsstdinfos/saveLimsStdInfo', this.formData, {individualType: 'json'}).then(res => {
            if (res.succeed) {
              _this.dialogTableVisible = false;
              this.$message.success('修改成功')
              _this.$emit('refresh')
            } else {
              this.$message.error(res.message)
            }
          }).catch(e => {this.$message.error(e.message)})
        }
      })
    },
    httpRequest: function (e) {
      let _this = this;
      let file = e.file;
      if (!file) {
        // 没有文件
        return false
      }
      //  _this.monitorForm.tableData[_this.curRowIndex].annexName1 = file.name
      let uploadFile = new FormData ()
      uploadFile.append('file', file)
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      // _this.axios.post('pass/baseManagement/v1/download/testSingleUpload', uploadFile, config).then(res => {
      // 文件目录
      let category = 'WJ/';
      _this.axios.post('pass/seaweedfs/v1/download/' + category, uploadFile, config).then(res => {
        // if (res.succeed) {
        if (res && res.name) {
          _this.formData.savePath = category + res.name // res.data
        } else {
          _this.$message.error('文件上传失败')
        }
      }).catch(e => {
        _this.$message.error(e.message)
      })
    },
    closeDialog () {
      this.$refs['monitorForm'].resetFields();
      this.formData = {}
      this.tableType = 0;
      this.tableTypeDsc = '新增标准项目';
    },
  },
  watch: {
    showFlag (arg) {
      let _this = this;
      _this.dialogTableVisible = true;
      if (_this.Params !== null) {
        this.formData = Object.assign({},_this.Params[0])
        this.selectDepartment(this.formData.companyNo)
        this.selectClass(this.formData.deptNo)
        _this.tableType = 1;
        _this.tableTypeDsc = '修改标准项目';
        
      } else {
        _this.tableType = 0;
        _this.seenNo = false;
        _this.tableTypeDsc = '新增标准项目';
      }
    }
  }
}
</script>
<style lang="less">
.customWidth_stan{
  width: 600px !important
}
</style>
