<template>
  <div>
    <Modal v-model="showModal" :mask-closable="false" width="1230">
      <p slot="header">{{modalTitle}}</p>
      <div>
        <Form id="edit-form" ref="formObj" :model="formObj" :rules="ruleValidate" :label-width="90" inline>
<!--          <Form-item label="委托方是否第一次送检" prop="firsted" class="width-48">-->
<!--            <Radio-group v-model="formObj.firsted">-->
<!--              <Radio v-for="item in judgeType" :key="item.value" :label="item.value">{{item.name}}</Radio>-->
<!--            </Radio-group>-->
<!--          </Form-item>-->
          <Form-item label="委托单位" prop="client" class="width-48">
            <AutoComplete :value="formObj.client" :down-data="customerData" @on-result-change="_cusNameChange"
                          name="client" placeholder="请输入或选择委托单位"
            ></AutoComplete>
          </Form-item>
          <Form-item label="联系人" prop="operation.person" class="width-48">
            <Input v-model="formObj.operation.person" name="operation.person" placeholder="请输入联系人"/>
          </Form-item>
          <Form-item label="联系电话" prop="operation.tel" class="width-48">
            <Input v-model="formObj.operation.tel" name="operation.tel" placeholder="请输入联系电话"/>
          </Form-item>
          <Form-item label="传真" prop="operation.fax" class="width-48">
            <Input v-model="formObj.operation.fax" name="operation.fax" placeholder="请输入传真"/>
          </Form-item>
          <Form-item label="省、市、区" prop="testedCityData" class="width-48">
            <CityNameCascader :value="testedCityData.join(',')" @on-result-change="_cascaderResult" name="tested">
            </CityNameCascader>
          </Form-item>
          <Form-item label="街道" prop="street" class="width-48">
            <Input v-model="formObj.street" name="street" placeholder="请输入街道"/>
          </Form-item>
          <Form-item label="邮编" prop="operation.postcode" class="width-48">
            <Input v-model="formObj.operation.postcode" name="operation.postcode" placeholder="请输入邮编"/>
          </Form-item>

          <Form-item label="E-mail" prop="operation.email" class="width-48">
            <Input v-model="formObj.operation.email" name="operation.email" placeholder="请输入E-mail"/>
          </Form-item>
          <Form-item label="委托日期：" prop="edate" class="width-48">
            <Date-picker v-model="formObj.edate" @on-change="_ctimeChange" type="date" split-panels style="width:100%;"
                         placeholder="请选择委托日期"></Date-picker>
          </Form-item>
          <Form-item label="委托费用：" prop="operation.fee" class="width-48">
            <Input v-model="formObj.operation.fee" @keydown.native="channelInputLimit" type="number" name="operation.fee" placeholder="请输入委托费用"/>
          </Form-item>
          <Form-item label="要求完成日期：" prop="odate" class="width-48">
            <Date-picker v-model="formObj.odate" @on-change="_odateChange" type="date" split-panels style="width:100%;"
                         placeholder="请选择要求完成"></Date-picker>
          </Form-item>
          <Form-item label="合同号：" prop="contractCode" class="width-48">
            <Input v-model="formObj.contractCode" name="contractCode" placeholder="请输入合同号" style="width: 465px;"/>
            <span @click="_selectcontractCode" style="font-size: 20px;color: #00b5ec;cursor: pointer" class="">+</span>
          </Form-item>
          <Form-item label="备注：" prop="remark" style="width: 99.8%">
            <Input v-model="formObj.remark" :rows="3" name="remark" type="textarea"
                   placeholder="请输入备注"/>
          </Form-item>
        </Form>
        <Col span="24">
          <!--          <btn-list :msg="btn" :open="searchOpen" :showSearchBtn="false" @on-result-change="_btnClick"-->
          <!--                    class="contHide"></btn-list>-->
          <btn-list :msg="btn" :open="searchOpen" :show-search-btn="false" @on-result-change="_btnClick"
                    class="contHide"></btn-list>
<!--          <Button @click="_add()" type="success">添加</Button>-->
        </Col>
        <Col span="24">
          <PTVXETable
            ref="pageTable"
            :form-id="formId"
            :table-height="500"
            :get-page="getPage"
            :icon-msg="iconMsg"
            @on-result-change="_tableResultChange">
            <vxe-table-column
              v-for="item in pageColumns"
              :key="item.key"
              :field="item.key"
              :title="item.title"
              :width="item.width"
              :min-width="200"
              :fixed="item.fixed?item.fixed:undefined"
              sortable
            >
              <template slot-scope="scope">
                <div v-if="item.key==='name'" @click.stop="_handleRow(scope)">
                  <el-input v-model="scope.row.name" @on-result-change="_judgeBasisChange" blur placeholder="请输入或选择样品名称" style="width: 150px;"
                  ></el-input>
                  <a @on-result-change="_judgeBasisChange" @click="_selectjudgeBasis(scope.$rowIndex)" style="font-size: 18px;" class="">+</a>
                </div>
                <div v-if="item.key==='spec'" @click.stop="_handleRow(scope)">
                  <el-input v-model="scope.row.spec" blur placeholder="请输入型号规格"
                  ></el-input>
                </div>
                <div v-if="item.key==='factoryNumber'" @click.stop="_handleRow(scope)">
                  <el-input v-model="scope.row.factoryNumber" blur placeholder="请输入出厂编号"
                  ></el-input>
                </div>
                <div v-if="item.key==='verification'" @click.stop="_handleRow(scope)">
                  <el-input v-model="scope.row.verification" blur placeholder="请输入或选择检定（校准）依据"
                  ></el-input>
                </div>
                <div v-if="item.key==='manufacturer'" @click.stop="_handleRow(scope)">
                  <el-input v-model="scope.row.manufacturer" blur placeholder="请输入制造单位"
                  ></el-input>
                </div>
                <div v-if="item.key==='remark'" @click.stop="_handleRow(scope)">
                  <el-input v-model="scope.row.remark" blur placeholder="请输入备注"
                  ></el-input>
                </div>
                <div v-if="item.key==='type'" @click.stop="_handleRow(scope)">
                  <Select v-model="scope.row.type">
                    <Option v-for="(item,index) in options" :key="item.name" :value="index">
                      {{ item.name }}
                    </Option>
                  </Select>
                </div>
                <div v-if="item.key==='quantity'" @click.stop="_handleRow(scope)">
                  <el-input
                    v-model="scope.row.quantity"
                    @keydown.native="channelInputLimit"
                    type="number"
                    placeholder="请输入数量"
                  />
                </div>

                <div v-if="item.key==='testFee'" @click.stop="_handleRow(scope)">
                  <el-input
                    v-model="scope.row.testFee"
                    @keydown.native="channelInputLimit"
                    type="number"
                    placeholder="请输入检定/校准费"
                  />
                </div>
                <div v-if="item.key==='repairFee'" @click.stop="_handleRow(scope)">
                  <el-input
                    v-model="scope.row.repairFee"
                    @keydown.native="channelInputLimit"
                    type="number"
                    placeholder="请输入调修费"
                  />
                </div>
                <div v-if="item.key==='elseFee'" @click.stop="_handleRow(scope)">
                  <el-input
                    v-model="scope.row.elseFee"
                    @keydown.native="channelInputLimit"
                    type="number"
                    placeholder="请输入其他费用"
                  />
                </div>
                <span v-else>{{scope.row[item.key]}}</span>
              </template>
            </vxe-table-column>
          </PTVXETable>
        </Col>
      </div>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult"></modal-footer>
      </div>
      <ContractModal ref="ContractModal" @on-result-change="_backContract" is-change></ContractModal>
      <EditModal ref="EditModal" @on-result-change="_backData" is-change />
      <importModal ref="importModal" @on-result-change="_inputBack"   aptitude-item></importModal>
    </Modal>
  </div>
</template>
<script>
/**
 * 添加编辑分包商
 */
import { lmsBaseDict, meterEntrust } from '../../../api'
import CityNameCascader from '../../../components/base/CityNameCascader'
import AutoComplete from '../../../components/base/AutoCompletes'
import importModal from '../../../components/import/DownloadTemplateImport'
import EditModal from './EditModal'
import ContractModal from './ContractModal'

export default {
  components: {
    EditModal,
    CityNameCascader,
    AutoComplete,
    importModal,
    ContractModal
  },
  data() {
    const validatefee = (rule, value, callback) => {
      if (this.formObj.operation.fee === '') {
        callback(new Error('内容不能为空'))
      } else {
        callback()
      }
    }
    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()
      }
    }
    const validateEdate = (rule, value, callback) => {
      if (this.formObj.edate === '') {
        callback(new Error('内容不能为空'))
      } else {
        callback()
      }
    }
    const validateOdate = (rule, value, callback) => {
      if (this.formObj.odate === '') {
        callback(new Error('内容不能为空'))
      } else {
        callback()
      }
    }
    return {
      formId: 'meterSendTestEditFormId',
      getPage: {
        records: []
      },
      testedCityData: [],
      customerData: [],
      searchOpen: true,
      judgeType: [{ value: 1, name: '是' }, { value: 0, name: '否' }],
      iconMsg: [
        {
          type: 'md-trash',
          id: 'go-out-test-meter-go-out-test-edit-remove-o',
          name: '删除'
        }
      ],
      pageColumns: [
        { title: '样品名称', key: 'name', width: 200 },
        { title: '型号规格', key: 'spec' },
        { title: '检定依据', key: 'verification' },
        { title: '出厂编号', key: 'factoryNumber' },
        { title: '制造单位', key: 'manufacturer' },
        { title: '检测类型', key: 'type' },
        { title: '数量', key: 'quantity' },
        { title: '检定/校准费', key: 'testFee' },
        { title: '调修费', key: 'repairFee' },
        { title: '其他费用', key: 'elseFee' },
        { title: '备注', key: 'remark' }
      ],
      btn: [
        {
          type: 'success',
          id: 'go-out-test-meter-go-out-test-edit-add',
          name: '添加'
        },
        {
          type: 'success',
          id: 'go-out-test-meter-go-out-test-edit-import',
          name: '导入'
        }
      ],
      options: [
        {
          name: '检定'
        },
        {
          name: '校准'
        },
        {
          name: '外观检查'
        }
      ],
      index: 0,
      id: '',
      modalTitle: '',
      subcontractorId: '',
      formObj: {
        firsted: 1,
        client: '',
        linkman: '',
        tel: '',
        email: '',
        address: '',
        remark: '',
        street: '',
        province: '',
        city: '',
        county: '',
        aptitude: [],
        assessFormSn: '',
        subArea: '',
        personCondition: '',
        edate: '',
        odate: '',
        contractCode: '',
        operation: {
          person: '',
          tel: '',
          fax: '',
          postcode: '',
          email: '',
          fee: ''
        },
        testedTemp: {
          testedName: '',
          testedContactor: '',
          testedContactorTel: '',
          testedTel: '',
          testedProvince: '',
          testedCity: '',
          testedCounty: '',
          testedStreet: ''
        }
      },
      ruleValidate: {
        testedCityData: [
          {
            required: true,
            message: '省市区不能为空',
            validator: validateRemark,
            trigger: 'blur'
          }
        ],
        client: [
          {
            required: true,
            validator: validateClient,
            message: '委托单位不能为空',
            trigger: 'blur'
          }
        ],
        edate: [
          {
            required: true,
            validator: validateEdate,
            message: '委托日期不能为空',
            trigger: 'blur'
          }
        ],
        odate: [
          {
            required: true,
            validator: validateOdate,
            message: '要求完成时间不能为空',
            trigger: 'blur'
          }
        ],
        'operation.fee': [
          {
            required: true,
            validator: validatefee,
            message: '委托费用不能为空',
            trigger: 'blur'
          }
        ],
        'operation.person': [
          { required: true, message: '联系人不能为空', trigger: 'blur' }
        ],
        'operation.tel': [
          { required: true, message: '联系电话不能为空', trigger: 'blur' }
        ]
        // testedCityData: [
        //   { required: true, message: '省市区不能为空', trigger: 'blur' }
        // ]
      },
      clearingWayList: ['款到后测试', '先测试后付款', '其他情况（）'],
      clearingWayListTemp: ['款到后测试', '先测试后付款', '其他情况（）'],
      showModal: false,
      footerList: [
        { id: '', name: '取消', type: '' },
        { id: '', name: '保存', type: 'primary' }
      ],
      aptitudeData: []
    }
  },
  // created() {
  //   this.$set(
  //     this.formObj,
  //     'tested',
  //     JSON.parse(JSON.stringify(this.testedTemp))
  //   )
  // },
  methods: {
    _importSample() {
      const data = {
        importUrl: '/meter/v1/sample/import_send_sample_pre',
        downloadUrl: '/meter/v1/excel/template/MeterSendSampleImport',
        title: '导入'
      }
      this.$refs.importModal._open(data, '样品导入')
    },
    _inputBack(data) {
      if (undefined !== data) {
        for (let i = 0; i < data.length; i++) {
          this.getPage.records.push(data[i])
        }
      }
    },
    _btnClick(msg) {
      this.$nextTick(function() {
        switch (msg) {
          case '添加':
            this._add()
            break
          case '导入':
            this._importSample()
            break
          case 'search':
            this.searchOpen = !this.searchOpen
            break
        }
      })
    },
    _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 if (this.customerData.indexOf(data) !== -1) {
        this._getQueryList(data)
        // 编辑的时候选择单位(互不影响)
        // this.cusName = data
        // this.formObj.customer.cname = data
      } else {
      }
    },
    _customerMatch(data) {
      // this.formObj.client = data
      this._getQueryList(data)
      console.log(data)
    },
    _cusNameQuery(query) {
      this.formObj.client = query
      console.log(query)
    },
    _ctimeChange(data) {
      console.log('时间', data)
      this.formObj.edate = data
    },

    _odateChange(data) {
      console.log('odate时间', data)
      this.formObj.odate = data
    },
    _backData(data) {
      console.log(typeof this.index)
      this.getPage.records[this.index].name = data.name
      this.getPage.records[this.index].aptitudeId = data.id
      this.getPage.records[this.index].verification = data.code + data.basis
    },
    _backContract(data) {
      console.log(data)
    },
    _selectjudgeBasis(index) {
      this.index = index
      this.$refs.EditModal._open()
    },
    _selectcontractCode() {
      this.$refs.ContractModal._open()
    },
    _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) {
      // 省、市、区
      console.log('数据')
      console.log(data)
      console.log('msg', 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.testedTemp.testedProvince = data.value[0]
        // this.formObj.testedTemp.testedCity = data.value[1]
        // this.formObj.testedTemp.testedCounty = data.value[0]

        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]]
        console.log('地址', this.testedCityData)
      }
    },
    _getJudgeBasisList(data) {
      const obj = { classify: 0 }
      if (data) {
        obj.stdNum = data
      }
      // this.$store.dispatch('StandardInfo/list', obj).then(() => {
      //   this.judgeBasisData = this.$store.state.StandardInfo.list
      // })
    },
    _judgeBasisChange(msg, data) {
      switch (msg) {
        case 'select':
          this.formObj.stdId = data.id
          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')
      }
    },
    _add() {
      const data = {
        name: '',
        spec: '',
        factoryNumber: '',
        quantity: '',
        type: ''
      }
      this.getPage.records.unshift(data)
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'selectIds':
          // this.selectIds = data
          break
        case 'iconClick':
          this._iconClick(data.name, data.rowData, data.rowIndex)
          break
        // case 'changeSize':
        //   this._page()
        //   break
      }
    },
    _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
      }
    },
    _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
        case '保存':
          this._ok()
          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)
          if (this.$string(this.id).isEmpty()) {
            // 添加
            const saveData = this.formObj
            saveData.sampleList = this.getPage.records
            this._save(saveData)
          } else {
            const saveData = this.formObj
            saveData.sampleList = this.getPage.records
            // 编辑
            this._edit(saveData)
          }
        } else {
          this.$Message.error('表单验证失败!')
          this._hideLoading()
        }
      })
    },
    _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() {
      this.showModal = true
      this._getList()
      this.$refs.formObj.resetFields()
      this._hideLoading()
      this.getPage.records = []
      this.id = ''
      this.formObj.id = ''
      this.formObj.operation.id = ''
      this.modalTitle = '出检委托单登记'
      this.formObj.edate = new Date()
      this.testedCityData = []
    },

    _openEdit(formObj) {
      this._getList()
      this.getPage.records = []
      this.showModal = true
      this.$refs.formObj.resetFields()
      this._hideLoading()
      this.id = ''
      this.modalTitle = '出检委托单编辑'
      console.log('编辑', formObj)
      this.id = formObj.id
      this.formObj = formObj
      this._showAddress(formObj)
      this._showTime(formObj)
      this.getPage.records = formObj.sampleList
      console.log(this.formObj)
    },
    _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.operation.person = result[0].contact
        this.formObj.operation.tel = result[0].mobile
        this.formObj.operation.fax = result[0].fax
        this.formObj.operation.email = result[0].email
        this.formObj.street = result[0].street
        this.formObj.operation.postcode = result[0].postcode
        this.testedCityData = [
          result[0].province,
          result[0].city,
          result[0].area
        ]
        if (result[0].province) {
          this.formObj.province = result[0].province
        }
        if (result[0].city) {
          this.formObj.city = result[0].city
        }
        if (result[0].area) {
          this.formObj.county = result[0].area
        }
      }
    },
    _getAptitudeList: async function() {
      const result = await lmsBaseDict.getItem('subcontractorAptitude')
      if (result) {
        this.aptitudeData = result
      }
    },
    _showTime(formObj) {
      if (this.formObj.odate === undefined) {
        this.formObj.odate = ''
      } else {
        this.formObj.odate = new Date(formObj.odate)
      }

      if (this.formObj.edate === undefined) {
        this.formObj.edate = ''
      } else {
        this.formObj.edate = new Date(formObj.edate)
      }
    },
    _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)
      }
    },
    _save: async function(data) {
      const result = await meterEntrust.saveOutEntrust(data)
      console.log(result)
      if (result) {
        this._resultChange('添加成功!')
      }
    },
    _edit: async function(data) {
      const result = await meterEntrust.editDTO(data)
      if (result) {
        this._resultChange('编辑成功!')
      }
    }
  }
}
</script>
