<template>
  <div>
    <Modal v-model="showModal" width="100" class="modal-footer-none full-screen">
      <p slot="header">{{modalTitle}}</p>
      <div>
        <!--内容-->
        <Row>
          <!--查询-->
          <Col span="24">
            <Form :label-width="110" v-show="searchOpen" inline onsubmit="return false">
              <label class="label-sign"></label>
              <Form-item label="样品编号:" class="search-item">
                <Input @on-enter="_formSearch" v-model="formObj.num" placeholder="请输入样品编号" clearable/>
              </Form-item>
              <Form-item label="样品名称:" class="search-item">
                <Input @on-enter="_formSearch" v-model="formObj.sampleName" placeholder="请输入样品名称" clearable/>
              </Form-item>
              <Form-item class="search-btn">
                <Button @click="_formSearch" type="primary">搜索</Button>
              </Form-item>
            </Form>
          </Col>
          <!--操作-->
          <Col span="24">
            <btn-list :msg="btn" @on-result-change="_btnClick" :show-search-btn="true" class="contHide">
              <template slot="processTask">
                <div class="fr process-task">
                  <el-checkbox v-model="formObj.onlyAbort" @change="_page" :true-label="1"
                               :false-label="0" size="medium">查看终止项目
                  </el-checkbox>
                </div>
              </template>
            </btn-list>
          </Col>
          <!-- 表格 -->
          <Col span="24">
            <PTVXETable
              ref="pageTable" :tableHeight="tableHeight" @on-result-change="_tableResultChange"
              :getPage="getPage"
              is-edit
              is-group
              select-data>
              <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"
                :edit-render="item.editCell?{autofocus: 'input'}:null"
                sortable
              >
                <!--可编辑模板-->
                <template v-slot:edit="scope">
                  <div v-if="item.detail"><a @click.stop="_detailModal(scope.row.sampleId)">{{scope.row[item.key]}}</a>
                  </div>
                  <div v-else-if="item.status">{{scope.row[item.key] === undefined ?'':scope.row[item.key].display}}
                  </div>
                  <div v-else-if="item.date">{{scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd'):''}}
                  </div>
                  <div v-else-if="item.key==='epibolyItem'">{{scope.row.epibolyItem?'是':'否'}}</div>
                  <div v-else-if="item.key==='qualified'">{{scope.row.qualified?scope.row.qualified.display:''}}</div>
                  <!--科室 start-->
                  <div v-else-if="item.key==='groupName'">
                    <el-select v-model="scope.row.groupName" @change="_groupChange" @click.native.stop="_handleRow(scope)"
                               transfer
                               size="small">
                      <el-option :label="item.name" :value="item.name" v-for="item in groupData"
                                 :key="item.name"></el-option>
                    </el-select>
                  </div>
                  <!--科室 end-->
                  <!--检测依据简称 start-->
                  <div v-else-if="item.key==='testBasisSm'">
                    <el-select v-model="scope.row.testBasisSm"
                               @change="_saveTestBasisSm(scope)"
                               placeholder="请选择检测依据简称"
                               size="small"
                               style="width:100%">
                      <el-option
                        v-for="item in testBasisSmList"
                        :key="item"
                        :label="item"
                        :value="item">
                      </el-option>
                    </el-select>
                  </div>
                  <!--检测依据简称 end-->
                  <!--检测依据名+号 start-->
                  <div v-else-if="item.key==='testBasisAndName'">
                    <AutoCompletesTestBasis :value="scope.row.testBasisAndName" :downData="testBasisData"
                                            @on-result-change="_testBasisChange" :handleObj="scope"
                                            placeholder="请选择检测依据" focus blur
                    ></AutoCompletesTestBasis>
                  </div>
                  <!--检测依据名+号 end-->
                  <!--检测方法 start-->
                  <div v-else-if="item.key==='testMethod'">
                    <AutoCompletes :value="scope.row.testMethod" :downData="testMethodData"
                                   @on-result-change="_testMethodChange" :handleObj="scope"
                                   placeholder="请选择检测方法" focus blur show-key="testMethod"
                    ></AutoCompletes>
                  </div>
                  <!--检测方法 end-->
                  <div v-else>{{scope.row[item.key]}}</div>
                </template>
                <template slot-scope="scope">
                  <div v-if="item.detail"><a @click.stop="_detailModal(scope.row.sampleId)">{{scope.row[item.key]}}</a>
                  </div>
                  <div v-else-if="item.status">{{scope.row[item.key] === undefined ?'':scope.row[item.key].display}}
                  </div>
                  <div v-else-if="item.date">{{scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd'):''}}
                  </div>
                  <div v-else-if="item.key==='epibolyItem'">{{scope.row.epibolyItem?'是':'否'}}</div>
                  <div v-else-if="item.key==='qualified'">{{scope.row.qualified?scope.row.qualified.display:''}}</div>
                  <div v-else>{{scope.row[item.key]}}</div>
                </template>
              </vxe-table-column>
            </PTVXETable>
          </Col>
        </Row>
      </div>
    </Modal>
  </div>
</template>
<script>
/* 查看样品（企业和政府） */
import { soilEntrust } from '../../../api'

export default {
  components: {},
  data() {
    return {
      showModal: false,
      selectData: [],
      selectIds: [],
      modalTitle: '检测项目',
      type: '', // 判断是企业或政府委托
      getPage: {},
      pageColumns: [
        { title: '产品', key: 'subClass', width: 200, fixed: 'left' },
        { title: '样品编号', key: 'num', width: 180, detail: true },
        { title: '样品名称', key: 'sampleName', width: 120 },
        { title: '样品大类', key: 'firstClass', width: 130 },
        { title: '样品细类', key: 'detectType', width: 120 },
        { title: '抽样单编号', key: 'samplingNum', width: 140 },
        { title: '检测项目', key: 'name', width: 200 },
        { title: '状态', key: 'progress', width: 120, status: true },
        { title: '检测科室', key: 'groupName', width: 130, editCell: true },
        { title: '省局项目ID', key: 'provinceItemId', width: 120 },
        {
          title: '检测依据简称',
          key: 'testBasisSm',
          width: 200,
          editCell: true
        },
        {
          title: '检测依据',
          key: 'testBasisAndName',
          width: 300,
          editCell: true
        },
        { title: '检测方法', key: 'testMethod', width: 200, editCell: true },
        { title: '判定依据', key: 'judgeBasisAndName', width: 300 },
        { title: '检测值', key: 'testValue', width: 120 },
        { title: '单位', key: 'unit', width: 120 },
        { title: '结果判定', key: 'qualified', width: 120 },
        { title: '检出限', key: 'detection', width: 120 },
        { title: '限量', key: 'limitDefault', width: 120 },
        { title: '是否分包', key: 'epibolyItem', width: 120 },
        { title: '接收日期', key: 'receiveDate', width: 120, date: true },
        { title: '抽样日期', key: 'samplingDate', width: 120, date: true },
        { title: '签发人', key: 'issuer', width: 120 },
        { title: '签发日期', key: 'issueDate', width: 120, date: true },
        { title: '下单日期', key: 'ctime', width: 120, date: true },
        { title: '说明', key: 'labRemark', width: 200 },
        { title: '备注', key: 'remark' }
      ],
      btn: [
        // {type: 'primary', id: 'food-sampling-list-item-match', name: '匹配省抽项目'},
        {
          type: 'error',
          id: 'ZBC',
          name: '删除'
        }
        // {type: '', id: 'food-sampling-list-reset-sc-id', name: '重置省局ID',},
      ],
      formObj: {
        contractId: '',
        samplingNum: '',
        name: '',
        num: '',
        samplingDateBegin: '',
        samplingDateEnd: '',
        receiveDateBegin: '',
        receiveDateEnd: '',
        ctimeBegin: '',
        ctimeEnd: '',
        testBasis: '',
        detectType: '',
        mateTestBasisSm: 0,
        hasProvinceId: 0,
        groupIds: '',
        sampleName: '',
        firstClass: '',
        onlyAbort: 0,
        qced: 0
      },
      receiveDateList: [],
      ctimeList: [],
      samplingDateList: [],
      searchOpen: false,
      groupData: [],
      testBasisSmList: [],
      testBasisData: [],
      testMethodData: [],
      currentRow: {},
      judgeList: [{ name: '是', value: 1 }, { name: '否', value: 0 }],
      // 检测科室
      selectGroupData: []
    }
  },
  computed: {
    tableHeight: function() {
      if (this.searchOpen) {
        return this.$tableHeight('', 320)
      } else {
        return this.$tableHeight('', 175)
      }
    }
  },
  mounted() {
    // this._getGroup()
  },
  methods: {
    // 搜索项检测科室变化
    _groupDataChange(data) {
      this.formObj.groupIds = data.join(',')
    },
    _handleRow(data) {
      this.currentRow = data.row
    },
    // 选择科室
    _groupChange(e) {
      const obj = this.groupData.find(item => item.name === e)
      if (obj) {
        this.$set(this.currentRow, 'groupId', obj.id)
        this.$set(this.currentRow, 'groupName', obj.name)
      }
      this._save()
    },
    // 检测依据结果
    _testBasisChange(msg, data, handleObj) {
      this._handleRow(handleObj)
      switch (msg) {
        case 'select':
          this.currentRow.testBasisAndName =
            data.testBasis + '  ' + data.testBasisName
          this.currentRow.testBasis = data.testBasis
          this.currentRow.testBasisId = data.stdId
          this.currentRow.testBasisName = data.testBasisName
          this.currentRow.groupId = data.groupId
            ? data.groupId
            : this.groupData[0].id
          this.currentRow.groupName = data.groupName
            ? data.groupName
            : this.groupData[0].name
          this._save()
          break
        case 'query':
          this.currentRow.testBasisAndName = data

          // 只要搜索就清空已填的值
          this.currentRow.testBasisName = ''
          this.currentRow.testBasisId = ''
          this.currentRow.testBasis = ''
          this._testBasisList(data)
          break
        case 'focus':
          this._testBasisList()
          break
        case 'blur':
          // 如果没有依据，则清空
          if (this.currentRow.testBasisId === '') {
            this.currentRow.testBasisAndName = ''
          }
          this._save()
          break
      }
    },
    // 抽样日期
    _samplingDateChange(data) {
      this.formObj.samplingDateBegin = data[0]
      this.formObj.samplingDateEnd = data[1]
    },
    // 接收日期
    _receiveChange(data) {
      this.formObj.receiveDateBegin = data[0]
      this.formObj.receiveDateEnd = data[1]
    },
    // 下单日期
    _ctimeChange(data) {
      this.formObj.ctimeBegin = data[0]
      this.formObj.ctimeEnd = data[1]
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'selectData':
          const selectIds = []
          for (let i = 0; i < data.length; i++) {
            selectIds.push(data[i].id)
          }
          this.selectIds = selectIds
          this.selectData = data
          break
        case 'changeSize':
          this._page()
          break
      }
    },
    _btnClick(msg) {
      switch (msg) {
        case '匹配省抽项目':
          this._matchItem()
          break
        case '删除':
          this._deleteSelected()
          break
        case '选择依据简称':
          this._selTestBasisSm()
          break
        case '重置省局ID':
          this._resetScId()
          break
        case '终止':
          this._operateItem(msg)
          break
        case '恢复终止项目':
          this._operateItem(msg)
          break
        case 'search':
          this.searchOpen = !this.searchOpen
          break
      }
    },
    _resetScId() {
      if (this.selectIds.length === 0) {
        this.$Modal.confirm({
          title: '提示',
          content: '请确认是否重置整个任务下所有检测项目的省局ID?',
          onOk: () => {
            this._resetScIdOk()
          }
        })
      } else {
        this._resetScIdOk()
      }
    },
    _matchItem() {
      const list = this.selectData
      for (let i = 0; i < list.length; i++) {
        const obj = this.selectData.find(item => item.name !== list[i].name)
        if (obj) {
          this.$Modal.confirm({
            title: '提示',
            content:
              '一次只能手动匹配同一分类下的同一项目，您选中的检测项目名称不同，是否继续？',
            onOk: () => {
              this.$refs.matchModal._open(
                this.selectIds,
                this.formObj.contractId
              )
            }
          })
          return
        }
      }
      this.$refs.matchModal._open(this.selectIds, this.formObj.contractId)
    },
    _matchChange(msg) {
      switch (msg) {
        case 'page':
          this._page()
          break
        case 'manual':
          this.$refs.tabModal._open(
            this.formObj.contractId,
            this.selectIds,
            this.selectData[0].samplingNum,
            this.selectData[0].provinceClassifyId
          )
          break
      }
    },
    _deleteSelected() {
      // 批量删除
      const ids = this.selectIds
      if (ids.length === 0) {
        this.$Message.warning('请选择一条或多条数据！')
      } else {
        this._deleteByIds(ids, '确定删除 ' + ids.length + ' 条记录？')
      }
    },
    _deleteByIds(ids, content) {
      this.$Modal.confirm({
        title: '提示',
        content: content,
        onOk: () => {}
      })
    },
    _resultChange(msg) {
      this._page()
      this.$Message.success(msg)
      this.selectIds = []
      this.$emit('on-result-change')
    },
    _formSearch() {
      this.$refs.pageTable._pageChange(1)
    },
    _page: async function() {
      Object.assign(this.formObj, this.$refs.pageTable._searchParams())
      console.log('this.formObj', this.formObj)
      const result = await soilEntrust.page(this.$serializeForm(this.formObj))
      if (result) {
        this.$refs.pageTable._hideLoading()
        this.getPage = result
      }
    },
    _open(id, type) {
      this.formObj = this.$resetFields(this.formObj)
      this.formObj.hasProvinceId = 0
      this.formObj.mateTestBasisSm = 0
      this.formObj.onlyAbort = 0
      this.formObj.contractId = id
      this.receiveDateList = []
      this.ctimeList = []
      this.samplingDateList = []
      this.type = type
      this.showModal = true
      this.currentRow = {}
      this.selectGroupData = []
      this._page()
    }
  }
}
</script>
