<template>
  <div>
    <Modal v-model="showModal" :mask-closable="false" width="1000">
      <p slot="header">{{modalTitle}}</p>
      <div>
        <Form id="edit-form" ref="formObj" :model="formObj" :rules="ruleValidate" :label-width="110" label-position="left" inline>
          <Form-item  label="委托单位" prop="client" style="width: 100%;margin-bottom: 5px;">
            <Input v-model="formObj.client" name="content" readonly/>
          </Form-item>
          <Form-item label="项目、内容" prop="content" style="width: 100%;margin-bottom: 5px;">
            <Input v-model="formObj.content" :rows="3"  type="textarea" name="content" readonly/>
          </Form-item>
<!--          <Form-item label="评审人员" prop="person" style="width: 100%;margin-bottom: 5px;">-->
<!--            <Input v-model="formObj.person" name="person" placeholder="请输入评审人员"/>-->
<!--          </Form-item>-->
            <Form-item label="检定/校准执行规程/规范：" prop="operation.requirements" style="width: 100%;margin-bottom: 5px;">
              <Input v-model="formObj.operation.requirements" :rows="2" readonly name="requirements" type="textarea" placeholder="请输入要求"/>
            </Form-item>
            <Form-item label="要求完成时间" prop="odate" style="width: 100%;margin-bottom: 5px;">
              <span>
                {{formObj.odate?$dateformat(formObj.odate,'yyyy-mm-dd'):''}}
              </span>

            </Form-item>
          <Form-item label="资质能否满足要求" prop="operation.aptituded" class="width-48" style="margin-bottom: 0px;">
             <span>
                {{formObj.operation.aptituded===1?'是':'否'}}
              </span>
          </Form-item>
          <Form-item label="设备及环境条件是否满足要求" prop="operation.environmented" class="width-48" style="margin-bottom: 0px;">
               <span>
                {{formObj.operation.environmented===1?'是':'否'}}
              </span>
          </Form-item>
          <Form-item label="规程/规范是否符合客户要求" prop="operation.standarded" class="width-48" style="margin-bottom: 0px;">
              <span>
                {{formObj.operation.standarded===1?'是':'否'}}
              </span>
          </Form-item>
          <Form-item label="人员是否具有能力" prop="operation.capable" class="width-48" style="margin-bottom: 0px;">
              <span>
                {{formObj.operation.capable===1?'是':'否'}}
              </span>
          </Form-item>
          <Form-item label="是否需要分包和分包方的能力评审" prop="operation.subcontracted" class="width-48" style="margin-bottom: 0px;">
              <span>
                {{formObj.operation.subcontracted===1?'是':'否'}}
              </span>
          </Form-item>
          <Form-item label="是否能在客户要求的时间内完成" prop="operation.completed" class="width-48" style="margin-bottom: 0px;">
               <span>
                {{formObj.operation.completed===1?'是':'否'}}
              </span>
          </Form-item>
          <Form-item label="其他问题的解决" prop="operation.otherQuestions" style="width: 99.8%;margin-bottom: 5px;" >
            <Input v-model="formObj.operation.otherQuestions" :rows="2" readonly name="other" type="textarea"
                   placeholder="请输入解决的问题"/>
          </Form-item>
          <Form-item label="评审结论" prop="operation.reviewConclusion" style="width: 99.8%;margin-bottom: 5px;">
            <Input v-model="formObj.operation.reviewConclusion" :rows="2" readonly name="verdict" type="textarea"
                   placeholder="请输入评审结论"/>
          </Form-item>

          <Form-item label="备注：" prop="operation.remark" style="width: 99.8%;margin-bottom: 5px;">
            <Input v-model="formObj.operation.remark" :rows="2"  readonly type="textarea" name="remark"
                   placeholder="请输入备注"/>
          </Form-item>
        </Form>
        <!--操作-->
      </div>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult"></modal-footer>
      </div>
    </Modal>
    <importModal ref="importModal" @on-result-change="_inputBack"   aptitude-item></importModal>
  </div>
</template>
<script>
/**
 * 添加编辑分包商
 */
import { lmsBaseDict, meterEntrust, meterContract } from '../../../api'
import importModal from '../../../components/import/DownloadTemplateImport'

export default {
  components: { importModal },
  data() {
    const validateRemark = (rule, value, callback) => {
      if (this.testedCityData.length === 0) {
        callback(new Error('内容不能为空'))
      } else {
        callback()
      }
    }
    const validateClient = (rule, value, callback) => {
      if (this.formObj.client === '') {
        callback(new Error('内容不能为空'))
      } else {
        callback()
      }
    }
    return {
      formId: 'meterSendTestEditFormId',
      getPage: {
        records: []
      },
      menusList: [{ name: '是', value: '1' }, { name: '否', value: '0' }],
      searchOpen: false,
      customerData: [],
      cityData: [],
      testedCityData: [],
      judgeType: [{ value: 1, name: '是' }, { value: 0, name: '否' }],
      iconMsg: [
        {
          type: 'ios-clock',
          id: 'meter-contract-review-add-edit-edit-operation',
          name: '编辑'
        },
        {
          type: 'ios-clock',
          id: 'meter-contract-review-add-edit-remove-operation',
          name: '删除'
        }
      ],
      pageColumns: [
        { title: '名称', key: 'name', width: 160 },
        { title: '型号', key: 'spec' },
        { title: '数量', key: 'quantity' },
        { title: '技术参数', key: 'technicalParameter' },
        { title: '生产厂家', key: 'manufacturer' },
        { title: '出厂编号', key: 'factoryNumber' },
        { title: '上次检定校准日期', key: 'lastTime', date: true },
        { title: '收费单位', key: 'unit' },
        { title: '单价/元', key: 'price' },
        { title: '总价/元', key: 'totalPrice' },
        { title: '备注', key: 'remark' }

        // {title: '限制范围或说明', key: 'limitDescription'},
      ],
      options: [
        {
          name: '检定'
        },
        {
          name: '校准'
        },
        {
          name: '外观检查'
        }
      ],
      btn: [
        {
          type: 'success',
          id: 'contract-file-meter-contract-review-add-edit-add',
          name: '添加'
        },
        {
          type: 'success',
          id: 'file-meter-contract-review-add-edit-import',
          name: '导入'
        }
      ],
      contractId: '',
      modalTitle: '',
      subcontractorId: '',
      formObj: {
        odate: '',
        contractId: '',
        client: '',
        operation: {
          aptituded: undefined,
          environmented: undefined,
          standarded: undefined,
          capable: undefined,
          subcontracted: undefined,
          completed: undefined,
          otherQuestions: undefined,
          reviewConclusion: undefined,
          technicalDirector: undefined,
          remark: undefined
        }
      },

      ruleValidate: {
        client: [
          {
            required: true,
            message: '委托单位不能为空',
            validator: validateClient,
            trigger: 'blur'
          }
        ],
        // person: [
        //   { required: true, message: '联系人不能为空', trigger: 'blur' }
        // ],
        // tel: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
        testedCityData: [
          {
            required: true,
            message: '省市区不能为空',
            validator: validateRemark,
            trigger: 'blur'
          }
        ]
      },

      clearingWayList: ['款到后测试', '先测试后付款', '其他情况（）'],
      clearingWayListTemp: ['款到后测试', '先测试后付款', '其他情况（）'],
      showModal: false,
      footerList: [{ id: '', name: '关闭', type: '' }],
      aptitudeData: []
    }
  },
  // created() {
  //   this.$set(
  //     this.formObj,
  //     'tested',
  //     JSON.parse(JSON.stringify(this.testedTemp))
  //   )
  // },
  methods: {
    _cusNameChange(msg, data) {
      // this.financeObj = {} // 清空维护发票信息的数据
      if (this.$string(this.id).isEmpty()) {
        // 添加的时候选择单位
        switch (msg) {
          case 'select':
            this._customerMatch(data)
            break
          case 'query':
            this._cusNameQuery(data)
            break
        }
      } else {
      }
    },
    _customerMatch(data) {
      this._getQueryList(data)
      console.log(data)
    },
    _cusNameQuery(query) {
      this.formObj.client = query
      console.log(query)
    },
    _ctimeChange(data) {
      console.log('时间', data)
      this.formObj.odate = data
      // this.formObj.ctimeBegin = data[0]
      // this.formObj.ctimeEnd = data[1]
    },
    _reviewTime(data) {
      console.log('时间', data)
      this.formObj.reviewTime = data
      // this.formObj.ctimeBegin = data[0]
      // this.formObj.ctimeEnd = data[1]
    },
    _judgeBasisChange(msg, data) {
      switch (msg) {
        case 'select':
          this.formObj.stdId = data.id
          this.formObj.code = data.stdNum
          this.formObj.name = data.name
          this.$refs.formObj.validateField('code')
          break
        case 'query':
          this.formObj.stdId = ''
          this.formObj.code = data.stdNum
          this.formObj.name = ''
          this._getJudgeBasisList(data.stdNum)
          break
        case 'focus':
          this._getJudgeBasisList()
          break
        case 'blur':
          if (this.formObj.stdId === '') {
            this.formObj.code = ''
            this._getJudgeBasisList()
          }
          this.$refs.formObj.validateField('code')
      }
    },
    _selectjudgeBasis(index) {
      console.log(index)
      this.index = index
      this.$refs.EditModal._open()
    },
    _backData(data) {
      console.log(typeof this.index)
      this.getPage.records[this.index].name = data.name
      this.getPage.records[this.index].aptitudeId = data.id
      console.log('返回的数据')
      console.log(data)
      console.log(this.getPage.records)
    },

    _inputBack(data) {
      if (undefined !== data) {
        for (let i = 0; i < data.length; i++) {
          this.getPage.records.push(data[i])
        }
      }
    },
    _add() {
      const data = {
        name: '',
        spec: '',
        factoryNumber: '',
        quantity: '',
        type: ''
      }
      this.getPage.records.unshift(data)
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'page':
          // this.getPage = this.$store.state.FoodJudgeBasis.page
          break
        case 'selectIds':
          // this.selectIds = data
          break
        case 'iconClick':
          this._iconClick(data.name, data.rowData, data.rowIndex)
          break
      }
    },
    _btnClick(msg) {
      this.$nextTick(function() {
        switch (msg) {
          case '导入':
            this._import()
            break
          case '添加':
            this._add()
            break
          case '提交':
            this._submitToReview()
            break
          case 'search':
            this.searchOpen = !this.searchOpen
            break
        }
      })
    },
    _import() {
      const data = {
        importUrl: '/meter/v1/sample_quote/import',
        downloadUrl: '/food/v1/excel/template/FoodAptitudeItem',
        title: '导入'
      }
      this.$refs.importModal._open(data, '资质项目管理导入')
    },
    // 省 市 区
    _cascaderResult(name, data, msg) {
      switch (name) {
        case 'cus':
          this._casChange(data, msg)
          break
        case 'tested':
          this._testedChange(data, msg)
          break
      }
    },
    _emptyProvince() {
      this.cityData = []
      this.testedCityData = []
      // this.formObj.tested.testedProvince = ''
      // this.formObj.tested.testedCity = ''
      // this.formObj.tested.testedCounty = ''
      // this.formObj.testedTemp.testedProvince = ''
      // this.formObj.testedTemp.testedCity = ''
      // this.formObj.testedTemp.testedCounty = ''
    },
    _testedChange(data, msg) {
      // 省、市、区
      if (msg === 'clear') {
        // this.formObj.tested.testedProvince = ''
        // this.formObj.tested.testedCity = ''
        // this.formObj.tested.testedCounty = ''
        this.formObj.testedTemp.testedProvince = ''
        this.formObj.testedTemp.testedCity = ''
        this.formObj.testedTemp.testedCounty = ''
        this.formObj.province = ''
        this.formObj.city = ''
        this.formObj.county = ''
        this.testedCityData = []
      } else {
        // this.formObj.tested.testedProvince = data.value[0]
        // this.formObj.tested.testedCity = data.value[1]
        // this.formObj.tested.testedCounty = data.value[2]
        this.formObj.province = data.value[0]
        this.formObj.city = data.value[1]
        this.formObj.county = data.value[2]
        this.testedCityData = [data.value[0], data.value[1], data.value[2]]
      }
    },

    _iconClick(res, data, index) {
      switch (res) {
        case '编辑':
          // this._editModal(true, data.id)
          break
        case '删除':
          // this._deleteById(data.id)
          console.log('点击了删除按钮')
          console.log(index)
          this.getPage.records.splice(index, 1)
          break
        case '操作日志':
          // this._record(data.id)
          break
      }
    },

    _selectAptitude(data) {
      console.log(data)
    },
    _handleRow(data) {
      this.currentRow = data.row
      this.currentIndex = data.rowIndex
    },
    channelInputLimit(e) {
      const key = e.key
      // 不允许输入'e'和'.'
      if (key === 'e' || key === '.') {
        e.returnValue = false
        return false
      }
      return true
    },
    /** *modal-footer */
    _footerResult(name) {
      switch (name) {
        case '关闭':
          this._cancel()
          break
      }
    },
    _hideLoading() {
      this.$refs.footerModal._hideLoading()
    },
    _resultChange(msg) {
      this.showModal = false
      this.$Message.success(msg)
      this.$emit('on-result-change')
      this._hideLoading()
    },
    _ok() {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize('edit-form')
          Object.assign(this.formObj, data)
          // 添加
          const updateData = this.formObj
          updateData.contractId = this.contractId
          this._contractReviewPass(updateData)
        } else {
          this.$Message.error('表单验证失败!')
          this._hideLoading()
        }
      })
    },

    _contractReviewPass: async function(data) {
      console.log('--_contractReviewPass--', data)
      const result = await meterContract.passContractReview(data)
      if (result) {
        this.$Message.success('评审通过成功!')
        this.showModal = false
        this.$emit('on-result-change')
      }
    },

    _wayResult(msg, data) {
      switch (msg) {
        case 'select':
          this.formObj.clearingWay = data
          break
        case 'query':
          this.formObj.clearingWay = data
          this._wayQuery(data)
          break
      }
    },
    _wayQuery(query) {
      if (query === '') {
        this.clearingWayList = this.clearingWayListTemp
      } else {
        this.clearingWayList = this.clearingWayListTemp.filter(
          item => item.indexOf(query) > -1
        )
      }
    },
    _cancel() {
      this.showModal = false
    },
    _open(formObj) {
      this.showModal = true
      this._getList()
      this.$refs.formObj.resetFields()
      this._emptyProvince()
      this._hideLoading()
      if (this.$string(formObj).isEmpty()) {
        this.getPage.records = []
        this.id = ''
        this.modalTitle = '合同/协议评审记录添加'
      } else {
        this.id = formObj.id
        this.formObj = formObj
        this.modalTitle = '合同评审记录'
        this._showTime(formObj)
      }
    },
    _openEdit(formObj) {
      this.showModal = true
      this.$refs.formObj.resetFields()
      this._hideLoading()
      this.contractId = formObj.id
      this.modalTitle = '合同评审记录'
      this.formObj.contractId = formObj.id
      this.formObj = formObj
      this._showAddress(formObj)
    },
    _showAddress(formObj) {
      this.testedCityData = []
      if (
        formObj.province !== undefined &&
        formObj.city !== undefined &&
        formObj.county !== undefined
      ) {
        this.testedCityData.push(formObj.province)
        this.testedCityData.push(formObj.city)
        this.testedCityData.push(formObj.county)
      }
    },
    _getList: async function() {
      const result = await meterEntrust.pageList()
      const list = []
      console.log('result', result)
      if (result) {
        for (let i = 0; i < result.length; i++) {
          console.log(result[i].cname)
          list.push(result[i].cname)
        }
        console.log('委托单位名单', list)
        this.customerData = list
      }
    },
    _getQueryList: async function(data) {
      const result = await meterEntrust.pageQueryList(data)
      console.log(result)
      if (result) {
        this.formObj.client = data
        this.formObj.person = result[0].contact
        this.formObj.tel = result[0].mobile
        this.formObj.fax = result[0].fax
        this.testedCityData = [
          result[0].province,
          result[0].city,
          result[0].area
        ]
      }
    },
    _getAptitudeList: async function() {
      const result = await lmsBaseDict.getItem('subcontractorAptitude')
      if (result) {
        this.aptitudeData = result
      }
    },
    _showTime(formObj) {
      // 回显资质类型
    },
    _save: async function(data) {
      const result = await meterContract.addQuote(data)
      console.log(result)
      if (result) {
        this._resultChange('添加成功!')
      }
    },
    _edit: async function(data) {
      const result = await meterEntrust.editDTO(data)
      console.log('修改后')
      console.log(result)
      if (result) {
        this._resultChange('编辑成功!')
      }
    }
  }
}
</script>
