<template>
  <div>
    <!--内容-->
    <div class="layout-content-padding">
      <div class="layout-content-main">
        <Row>
          <!--查询-->
          <Col span="24" style="margin-top: 10px">
            <Form v-show="searchOpen" id="formId" :label-width="90" inline onsubmit="return false">
              <label class="label-sign"></label>
              <Form-item class="search-item" label="委托单位:">
                <Input v-model="formObj.client" name="client" placeholder="请输入委托单位" clearable @on-enter="_formSearch"/>
              </Form-item>
              <Form-item class="search-item" label="委托编号:">
                <Input v-model="formObj.entrustCode" name="entrustCode" placeholder="请输入委托编号" clearable @on-enter="_formSearch"/>
              </Form-item>
              <Form-item class="search-item" label="样品名称:">
                <Input v-model="formObj.name" name="name" placeholder="请输入样品名称" clearable @on-enter="_formSearch"/>
              </Form-item>

              <Form-item class="search-item" label="样品编号:">
                <Input v-model="formObj.code" name="code" placeholder="请输入样品编号" clearable @on-enter="_formSearch"/>
              </Form-item>

              <Form-item class="search-btn">
                <Button type="primary" @click="_formSearch">搜索</Button>
              </Form-item>
            </Form>
          </Col>
          <!--操作-->
          <Col span="24">

            <btn-list :msg="btn" :open="searchOpen" :show-search-btn="true" class="contHide"
                     @on-result-change="_btnClick"></btn-list>
          </Col>
          <!--表格-->
          <Col span="24">
            <PTVXETable ref="pageTable" :table-height="tableHeight" :form-id="formId" :loading="true"
                        :get-page="getPage" :icon-msg="iconMsg" select-data @on-result-change="_tableResultChange">
              <vxe-table-column
                v-for="item in pageColumns"
                :key="item.key"
                :field="item.key"
                :title="item.title"
                :min-width="item.width?item.width:200"
                :fixed="item.fixed?item.fixed:undefined" sortable>
                <template slot-scope="scope">
                   <span v-if="item.key==='type'">
                      <span v-if="scope.row[item.key]===0">
                          检定
                      </span>
                      <span v-else-if="scope.row[item.key]===1">
                          校准
                      </span>
                       <span v-else-if="scope.row[item.key]===2">
                          外观检查
                      </span>
                  </span>
                  <span v-else-if="item.key==='progress'">{{scope.row[item.key].display}}</span>
                  <span v-else>{{scope.row[item.key]}}</span>
                </template>
              </vxe-table-column>
            </PTVXETable>
          </Col>
        </Row>
      </div>
    </div>
    <CertificateMake ref="itemOriginalRecordModal" @on-result-change="_resultRecord"></CertificateMake>
    <CertificateMakeLook ref="itemOriginalRecordLookModal" @on-result-change="_resultRecord"></CertificateMakeLook>
    <CreateReport ref="CreateReport"></CreateReport>
    <SelectOriTempRecord ref="SelectOriTempRecord" @on-result-change="_certificateSelectBack"></SelectOriTempRecord>
    <CarManage ref="carEdit"></CarManage>
    <InstruMentEdit ref="InstruEdit"></InstruMentEdit>
    <operationModal ref="operationModal"></operationModal>
    <FileManage ref="FileManage"></FileManage>
    <assignPerson ref="userModal" is-change @on-result-change="_userData"></assignPerson>
    <SelectOriTempRecordExcel ref="SelectOriTempRecordExcel" @on-result-change="_certificateSelectExcelBack"></SelectOriTempRecordExcel>
  </div>
</template>
<script>
import CertificateMake from '../../meter-certificate/CertificateMake'
import CertificateMakeLook from '../../meter-certificate/CertificateMakeLook'
import { meterSample } from '../../../api'
import operationModal from '../../../components/operation/Operation'
import SelectOriTempRecordExcel from '../../meter-send/sample-input/SelectOriTempRecordExcel'
import assignPerson from '../../../components/user-info-single/assignPerson'
import CreateReport from './CreateReport'
import CarManage from './CarManage'
import InstruMentEdit from './InstrumentEdit'
import SelectOriTempRecord from './SelectOriTempRecord'
export default {
  components: {
    CreateReport,
    CarManage,
    assignPerson,
    InstruMentEdit,
    SelectOriTempRecordExcel,
    operationModal,
    SelectOriTempRecord,
    CertificateMake,
    CertificateMakeLook
  },
  data() {
    return {
      currentComponent: '',
      formId: 'meterSubcontractorFormId',
      searchOpen: false,
      btn: [
        {
          type: 'success',
          id: '',
          name: '提交至审核'
        },
        {
          type: 'success',
          id: '',
          name: '提交'
        }
      ],
      iconMsg: [
        {
          type: 'ios-bookmarks',
          id: 'meter-certificate-make-spread-js-make',
          name: '编制证书'
        },
        {
          type: 'ios-bookmarks',
          id: 'meter-certificate-make-pageoffice-make',
          name: '在线编制证书'
        },
        {
          type: 'ios-bookmarks',
          id: 'meter-out-personal-task-create-o',
          name: '按模板编制证书'
        },
        // {
        //   type: 'md-create',
        //   id: '',
        //   name: '编辑'
        // },
        {
          type: 'md-car',
          id: '',
          name: '车辆管理'
        },
        { type: 'md-cloud', id: '', name: '附件' }
        // { type: 'md-remove-circle', id: '', name: '删除' },
        // {
        //   type: 'ios-clock',
        //   id: '',
        //   name: '操作日志'
        // }
      ],
      formObj: {
        client: undefined,
        code: undefined,
        name: undefined,
        entrustCode: undefined
      },
      selectIds: [],
      selectData: [],
      getPage: {},
      pageColumns: [
        { title: '样品名称', key: 'name', width: 120 },
        { title: '样品编号', key: 'code', width: 120 },
        { title: '型号规格', key: 'spec', width: 100 },
        { title: '状态', key: 'progress', width: 100 },
        { title: '证书是否编制', key: 'onlineReported', width: 120 },
        { title: '证书编号', key: 'reportCode', width: 150 },
        { title: '出厂编号', key: 'factoryNumber' },
        { title: '检测类型', key: 'type' },
        { title: '委托单位', key: 'client', width: 200 },
        { title: '联系人', key: 'person', width: 120 },
        { title: '联系电话', key: 'tel', width: 120 },
        { title: '详细地址', key: 'address', width: 250 },
        { title: '数量', key: 'quantity' },
        { title: '备注', key: 'remark' }
      ]
    }
  },
  computed: {
    tableHeight: function() {
      if (this.searchOpen) {
        return this.$tableHeight('search')
      } else {
        return this.$tableHeight('noSearch')
      }
    }
  },
  mounted() {
    this._page()
  },
  methods: {
    _btnClick(msg, componentName) {
      this.currentComponent = componentName
      this.$nextTick(function() {
        switch (msg) {
          case '生成':
            this._create()
            break
          case '提交':
            this._submitToCheck()
            break
          case '提交至审核':
            this._selectToReportReview()
            break
          case '添加':
            this._editModal(false)
            break
          case 'search':
            this.searchOpen = !this.searchOpen
            break
        }
      })
    },
    _selectToReportReview() {
      const ids = this.selectIds
      const data = this.selectData
      if (ids.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        for (let i = 0; i < data.length; i++) {
          if (
            data[i].onlineReported === undefined ||
            data[i].onlineReported === '否'
          ) {
            this.$Message.warning(
              '您选择的样品编号为' + data[i].code + '暂未编制证书，无法提交！'
            )
            return false
          }
        }
        this.$refs.userModal._open('salesman')
      }
    },
    _userData(data, msg) {
      if (msg === 'salesman') {
        this._distributeCertificateCheck(data)
      }
    },

    _distributeCertificateCheck: async function(data) {
      const result = await meterSample.selectToReportCheck({
        ids: this.selectIds,
        userId: data.id,
        user: data.realname
      })
      if (result) {
        await this._page()
        this.$Message.success('分配成功！')
      }
    },
    _certificateSelectBack(data) {
      if (data) {
        // this.$refs.itemOriginalRecordModal._open(
        //   data.sampleId,
        //   data.tempId,
        //   data.dataSource
        // )
        this._makeCode(data)
      } else {
        const ids = this.selectIds
        if (ids.length === 0) {
          this.$Message.warning('请至少选择一条数据!')
        } else {
          // this._appendOriginalRecord()
        }
      }
    },
    _makeCode: async function(data) {
      const result = await meterSample.makeCode(data)
      if (result) {
        if (result === '' || result === undefined) {
          this.$Message.warning('证书编号暂未生成！')
          return false
        }
        data.dataSource.cc = result
        this.$refs.itemOriginalRecordModal._open(
          data.sampleId,
          data.tempId,
          data.dataSource
        )
      }
    },
    _submitToReview() {
      this._submitByContractIds('委托评审')
    },
    _submitByContractIds(cont) {
      const ids = this.selectIds
      if (ids.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        this.$Modal.confirm({
          title: '提示',
          content: '确定要把这 ' + ids.length + ' 条记录提交到' + cont + '？',
          onOk: () => {
            const result = meterSample.submit(ids)
            if (result) {
              console.log(result)
            }
          }
        })
      }
    },
    _create() {
      const selectData = JSON.parse(JSON.stringify(this.selectData))
      console.log(selectData)
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        this.$refs.CreateReport._open(this.selectData)
      }
    },

    _submitToCheck() {
      if (this.selectData.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        for (let i = 0; i < this.selectData.length; i++) {
          if (this.selectData[i].onlineReported === '否') {
            this.$Message.warning(
              '您选择的样品编号为' +
                this.selectData[i].code +
                '的样品暂未生成报告请确认！'
            )
            return false
          }
        }
        this.$Modal.confirm({
          title: '提示',
          content: '确定提交' + this.selectIds.length + '条记录？',
          onOk: () => {
            this._submit(this.selectIds)
          }
        })
      }
    },
    _submit: async function(data) {
      const result = await meterSample.submitReportToCheck(data)
      if (result) {
        this.$Message.success('提交成功！')
        await this._page()
      }
    },
    _iconClick(res, data, componentName) {
      this.currentComponent = componentName
      this.$nextTick(function() {
        switch (res) {
          case '编制证书':
            this._makeCertificate(data)
            break
          case '在线编制证书':
            this._makeCertificateExcel(data)
            break
          case '按模板编制证书':
            this._makeCertificateExcelByTemp(data)
            break
          case '仪器领用':
            this.$refs.InstruEdit._open()
            break
          case '车辆管理':
            this.$refs.carEdit._open()
            break
          case '编辑':
            // this._editModal(true, data.id)
            this._personModal(data)
            break
          case '资质项目':
            this._itemModal(data.id)
            break
          case '附件':
            this._upload(data.id)
            break
          case '删除':
            this._deleteByIds([data.id])
            break
          case '操作日志':
            this._record(data.id)
            break
        }
      })
    },
    _personModal(data) {
      this._previewEdit(data.id)
    },
    _makeCertificate(data) {
      if (data.onlineReported === '否' || undefined === data.recordId) {
        console.log('click')
        this.$refs.SelectOriTempRecord._open(data.id, data)
      } else {
        this._itemOriginalRecordLook(data, 'write')
      }
    },
    _resultRecord() {
      this._page()
      this.$emit('on-result-change')
    },
    _itemOriginalRecordLook(data, name) {
      if (
        data.recordId === null ||
        undefined === data.recordId ||
        data.recordId === ''
      ) {
        this.$Message.warning('证书暂未编制！')
      } else {
        this.$refs.itemOriginalRecordLookModal._open(
          data.recordId,
          name,
          data.id
        )
      }
    },
    // 预览/编制报告
    async _previewEdit(id) {
      const result = await meterSample.reportPreview(id)
      if (result) {
        this.$openWindowModeless({
          objectKey: result.objectKey,
          id: id,
          isReport: 0
        })
      }
    },
    _record(id) {
      this.$refs.operationModal._open(id)
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'iconClick':
          this._iconClick(data.name, data.rowData, data.componentName)
          console.log('操作按钮点击后的值', data)
          break
        case 'selectData':
          this.selectData = data
          this.selectIds = []
          for (let i = 0; i < data.length; i++) {
            this.selectIds.push(data[i].id)
          }
          break
        case 'changeSize':
          this._page()
          break
      }
    },
    _page: async function() {
      Object.assign(this.formObj, this.$refs.pageTable._searchParams())
      console.log('this.formObj', this.formObj)
      const result = await meterSample.pageCertificateMake(this.formObj)
      if (result) {
        this.$refs.pageTable._hideLoading()
        this.getPage = result
      }
    },
    _formSearch() {
      this.$refs.pageTable._pageChange(1)
    },
    // 删除
    _deleteByIds(ids, content) {
      this.$Modal.confirm({
        title: '提示',
        content: content || '确定删除该记录？',
        onOk: () => {
          this._delete(ids)
        }
      })
    },
    // 编辑&添加
    _editModal(edit, id) {
      if (edit) {
        // 编辑
        this._getById(id)
      } else {
        // 添加
        this.$refs.editSubcontractorModal._open()
      }
    },
    // 追加项目
    _itemModal(data) {
      this.$refs.refModal._open(data)
    },

    _upload(id) {
      // 上传文件
      this.$refs.FileManage._open(id, 'subcontractorId')
    },
    _getById: async function(id) {
      const result = await meterSample.getById(id)
      if (result) {
        this.$refs.editSubcontractorModal._openEdit(result)
      }
    },
    _delete: async function(ids) {
      const result = await meterSample.deleteById(ids)
      if (result) {
        this._formSearch()
        this.$Message.success('删除成功！')
      }
    },

    _makeCertificateExcel(data) {
      if (data.onlineReported === '否') {
        this.$refs.SelectOriTempRecordExcel._open(data.id, data)
      } else {
        this._reportMakeLook(data)
      }
    },
    _makeCertificateExcelByTemp(data) {
      this.$refs.SelectOriTempRecordExcel._open(data.id, data)
    },
    _reportMakeLook: async function(data) {
      const result = await meterSample.getCertificateReport(data.id)
      if (result) {
        this._viewReport(result)
      }
    },
    _viewReport(data) {
      if (data) {
        this.$openWindowModeless({
          objectKey: data.objectKey,
          idType: 10,
          id: data.id,
          isReport: 4
        })
      }
    },
    _certificateSelectExcelBack(data) {
      if (data) {
        this._makeCodeExcel(data)
      } else {
        const ids = this.selectIds
        if (ids.length === 0) {
          this.$Message.warning('请至少选择一条数据!')
        } else {
          // this._appendOriginalRecord()
        }
      }
    },
    _makeCodeExcel: async function(data) {
      // this.$refs.pageTable._hideLoading()
      this.$refs.pageTable._showLoading()
      const result = await meterSample.generateExcelReport(data)
      if (result) {
        await this._page()
        this.$refs.pageTable._hideLoading()
        if (result === null || result === undefined) {
          this.$Message.warning('证书编制失败，请联系管理员！')
          return false
        } else {
          this.$emit('on-result-change')
          this._viewReport(result)
        }
      }
    }
  }
}
</script>
