<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">
            </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: 'name', width: 160 },
        { title: '试验项目英文简写', key: 'shortName', width: 140 },
        { title: '大类', key: 'mainType', width: 140 },
        { title: '小类', key: 'smallType' },
        { title: '检测依据', key: 'testBasis', width: 180 },
        { title: '试验方法', key: 'testMethod', width: 180 },
        { title: '状态', key: 'status', width: 180, status: true }
      ],
      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',},
      ],
      sampleId: '',
      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
    },
    // 科室
    _getGroup() {
      this.$store.dispatch('LmsUserGroup/list').then(() => {
        this.groupData = this.$store.state.LmsUserGroup.list
      })
    },
    // 选择科室
    _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()
    },
    // 获取方法简称
    _getTestBasisSm(data) {
      this.$store
        .dispatch('FoodItem/listAbbreviationByItem', { ids: data.row.id })
        .then(() => {
          const result = this.$store.state.FoodItem.list
          if (result) {
            this.testBasisSmList = result
          } else {
            this.testBasisSmList = []
          }
        })
    },
    // 方法简称(只是这个界面同批量的方法一样)
    _saveTestBasisSm(data) {
      this.currentRow = data.row
      this.$store
        .dispatch('FoodItem/assignmentAbbreviation', {
          ids: this.currentRow.id,
          abbreviation: this.currentRow.testBasisSm
        })
        .then(() => {
          const result = this.$store.state.FoodItem.success
          if (result) {
            // 不要刷新表格,只刷新当前行数据
            this.$store
              .dispatch('FoodItem/getItemByContract', {
                id: this.currentRow.id,
                contractId: this.formObj.contractId,
                page: 1,
                rows: 1,
                qced: 0
              })
              .then(() => {
                const newObj = this.$store.state.FoodItem.page.records
                if (newObj && newObj.length > 0) {
                  this.$set(
                    this.currentRow,
                    'testBasisAndName',
                    newObj[0].testBasisAndName ? newObj[0].testBasisAndName : ''
                  )
                  this.$set(
                    this.currentRow,
                    'testBasisId',
                    newObj[0].testBasisId ? newObj[0].testBasisId : ''
                  )
                  this.$set(
                    this.currentRow,
                    'testBasisName',
                    newObj[0].testBasisName ? newObj[0].testBasisName : ''
                  )
                  this.$set(
                    this.currentRow,
                    'testBasis',
                    newObj[0].testBasis ? newObj[0].testBasis : ''
                  )
                  this.$set(
                    this.currentRow,
                    'testMethod',
                    newObj[0].testMethod ? newObj[0].testMethod : ''
                  )
                  this.$set(
                    this.currentRow,
                    'groupName',
                    newObj[0].groupName ? newObj[0].groupName : ''
                  )
                  this.$set(
                    this.currentRow,
                    'groupId',
                    newObj[0].groupId ? newObj[0].groupId : ''
                  )
                }
              })
          }
        })
    },
    // 获取检测依据
    _testBasisList(data) {
      const obj = {}
      if (this.currentRow.name) {
        obj.name = this.currentRow.name
      } else {
        // 没有填检测项目检测依据的下拉就为空
        this.testBasisData = []
        return
      }
      if (data) {
        obj.testBasis = data
      }
      this.$store.dispatch('FoodAptitudeItem/getTestBasis', obj).then(() => {
        this.testBasisData = this.$store.state.FoodAptitudeItem.list
      })
    },

    // 检测依据结果
    _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
      }
    },
    // 获取检测方法
    _testMethodList(testMethod) {
      const obj = {}
      if (this.currentRow.name && this.currentRow.testBasisId) {
        obj.name = this.currentRow.name
        obj.stdId = this.currentRow.testBasisId
      } else {
        this.testMethodData = []
        return
      }
      if (testMethod) {
        obj.testMethod = testMethod
      }
      this.$store.dispatch('FoodAptitudeItem/getTestMethod', obj).then(() => {
        this.testMethodData = this.$store.state.FoodAptitudeItem.list
      })
    },
    // 检测方法结果
    _testMethodChange(msg, data, handleObj) {
      this._handleRow(handleObj)
      switch (msg) {
        case 'select':
          this.$set(this.currentRow, 'testMethod', data.testMethod)
          // testMethodTemp 临时存在
          this.$set(this.currentRow, 'testMethodTemp', data.testMethod)
          // 查询科室
          this.$store
            .dispatch('FoodAptitudeItem/getGroupInfo', {
              name: this.currentRow.name,
              stdId: this.currentRow.testBasisId,
              testMethod: this.currentRow.testMethod
            })
            .then(() => {
              const groupObj = this.$store.state.FoodAptitudeItem.model
              this.$set(this.currentRow, 'groupId', groupObj.groupId)
              this.$set(this.currentRow, 'groupName', groupObj.groupName)
              this._save()
            })
          break
        case 'query':
          this.$set(this.currentRow, 'testMethod', data.testMethod)
          this.$set(this.currentRow, 'testMethodTemp', '')
          this._testMethodList(data.testMethod)
          break
        case 'focus':
          this._testMethodList()
          break
        case 'blur':
          // 只能选择检测方法
          if (
            this.currentRow.testMethodTemp === '' ||
            this.currentRow.testMethodTemp === undefined
          ) {
            this.$set(this.currentRow, 'testMethod', '')
          }
          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 'page':
          this.getPage = this.$store.state.FoodItem.page
          this.selectIds = []
          break
        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
      }
    },
    // 恢复、终止
    _operateItem(name) {
      const ids = this.selectIds
      if (ids.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else if (name === '终止') {
        this.$Modal.confirm({
          title: '提示',
          content: '确定要' + name + '这 ' + ids.length + ' 条项目？',
          onOk: () => {
            this.$refs.reasonModal._open('终止原因')
          }
        })
      } else if (name === '恢复终止项目') {
        this.$store
          .dispatch('FoodItem/restoreVerification', {
            ids: this.selectIds.join(',')
          })
          .then(() => {
            const result = this.$store.state.FoodItem.success
            this._restore(result)
          })
      }
    },
    // 终止项目恢复
    _restore(result) {
      if (result !== '') {
        this.$Modal.confirm({
          title: '提示',
          content: result,
          onOk: () => {
            this.$store
              .dispatch('FoodItem/projectRestore', {
                ids: this.selectIds.join(','),
                contractId: this.formObj.contractId,
                deleteReport: 1
              })
              .then(() => {
                this._resultChange('恢复成功!')
              })
          }
        })
      } else {
        this.$store
          .dispatch('FoodItem/projectRestore', {
            ids: this.selectIds.join(','),
            contractId: this.formObj.contractId,
            deleteReport: 0
          })
          .then(() => {
            this._resultChange('恢复成功!')
          })
      }
    },
    // 原因返回的结果
    _reasonResult(data, msg) {
      const temp = {
        reason: data,
        ids: this.selectIds.join(','),
        contractId: this.formObj.contractId
      }
      if (msg === '终止原因') {
        this.$store.dispatch('FoodItem/archivesStop', temp).then(() => {
          this._resultChange('终止成功!')
        })
      }
    },
    _resetScId() {
      if (this.selectIds.length === 0) {
        this.$Modal.confirm({
          title: '提示',
          content: '请确认是否重置整个任务下所有检测项目的省局ID?',
          onOk: () => {
            this._resetScIdOk()
          }
        })
      } else {
        this._resetScIdOk()
      }
    },
    _resetScIdOk() {
      const obj = { contractId: this.formObj.contractId }
      if (this.selectIds.length) {
        obj.ids = this.selectIds.join(',')
      }
      this.$store.dispatch('FoodItem/resetProvinceItemId', obj).then(() => {
        if (this.$store.state.FoodItem.success) {
          this.$Message.success('操作成功！')
          this._page()
        }
      })
    },
    // 选择检测依据简称
    _selTestBasisSm() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条检测项目！')
      } else {
        this.$store
          .dispatch('FoodItem/listAbbreviationByItem', {
            ids: this.selectIds.join(',')
          })
          .then(() => {
            const result = this.$store.state.FoodItem.list
            // 弹出选择框
            this.$refs.basisSmModal._open(this.selectIds, result)
          })
      }
    },
    _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: () => {
          this.$store
            .dispatch('FoodItem/deleteItemByIds', { ids: ids.join(',') })
            .then(() => {
              this._resultChange('删除成功!')
            })
        }
      })
    },
    _resultChange(msg) {
      if (this.$store.state.FoodItem.success) {
        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())
      this.formObj = this.$serializeForm(this.formObj)
      this.formObj.sampleId = this.sampleId
      const result = await soilEntrust.experimentPage(
        this.$serializeForm(this.formObj)
      )
      if (result) {
        this.$refs.pageTable._hideLoading()
        this.getPage = result
        console.log(result)
      }
    },
    _open(id, type) {
      this.sampleId = id
      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()
    },
    _detailModal(id) {
      this.$store.dispatch('FoodSample/getByGovernId', id).then(() => {
        this.$refs.governSampleDetail._open(
          this.$store.state.FoodSample.governModel
        )
      })
    },
    // 保存  除结果判定(除手工判定)
    _save() {
      let tempBool = true
      setTimeout(() => {
        if (tempBool) {
          this.$refs.pageTable._showLoading()
        }
      }, 1500)
      const item = this.currentRow
      const obj = {
        unit: item.unit,
        testMethod: item.testMethod,
        limitDefault: item.limitDefault,
        limitValue: item.limitValue,
        compareSymbol: item.compareSymbol,
        limitType: item.limitType,
        judged: item.judged,
        detection: item.detection,
        labRemark: item.labRemark,
        microbeN: item.microbeN ? item.microbeN : 0,
        microbeC: item.microbeC ? item.microbeC : 0,
        microbeM: item.microbeM ? item.microbeM : 0,
        microbeBm: item.microbeBm ? item.microbeBm : 0,
        qualified: item.qualified.value,
        subClass: item.subClass,
        testBasisSm: item.testBasisSm,
        testBasisName: item.testBasisName,
        testBasis: item.testBasis,
        singleConclusion: item.singleConclusion,
        groupId: item.groupId,
        groupName: item.groupName
      }
      if (item.testBasisId) {
        obj.testBasisId = item.testBasisId
      }
      if (item.judgeBasisId) {
        obj.judgeBasisId = item.judgeBasisId
        obj.judgeBasis = item.judgeBasis
        obj.judgeBasisName = item.judgeBasisName
      } else {
        obj.judgeBasis = item.judgeBasis
        obj.judgeBasisName = item.judgeBasisName
      }
      const data = {
        id: item.id,
        obj: obj
      }
      this.$store.dispatch('FoodItem/itemEdit', data).then(() => {
        if (this.$store.state.FoodItem.success) {
          tempBool = false
          this.$refs.pageTable._hideLoading()
        } else {
          this.$Message.error('保存失败')
          tempBool = false
          this.$refs.pageTable._hideLoading()
        }
      })
    }
  }
}
</script>
