<template>
  <div>
    <Modal v-model="showModal" width="1100" class="modal-footer-none">
      <p slot="header">{{modalTitle}}</p>
      <div>
        <!--内容-->
        <Row>
          <!--查询-->
          <Col span="24">
            <Form id="formId" :label-width="80" inline onsubmit="return false">
              <label class="label-sign"></label>
              <Form-item label="检定项目:" class="search-item">
                <Input v-model="formObj.name" @on-enter="_formSearch" placeholder="请输入样品名称" clearable/>
              </Form-item>
              <Form-item class="search-btn" style="margin-left: -10px">
                <Button @click="_formSearch" type="primary">搜索</Button>
              </Form-item>
            </Form>
          </Col>
          <Col span="24">

            <btn-list :msg="btn" :open="searchOpen" :show-search-btn="true" @on-result-change="_btnClick"
                      class="contHide"></btn-list>
          </Col>
          <Col span="24">
            <PTVXETable ref="pageTable" :table-height="tableHeight" :form-id="formId" :get-page="getPage"
                         @on-result-change="_tableResultChange" 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" sortable>
                <template slot-scope="scope">
                  <div v-if="item.detail"><a @click.stop="_detailModal(scope.row.id)">{{scope.row[item.key]}}</a></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==='jobOut'">
                     {{scope.row[item.key]===1?'是':'否'}}
                  </div>
                  <span v-else-if="item.key==='singleJudge'">
                     {{ scope.row[item.key]===undefined?'':scope.row[item.key].display }}
                   </span>
<!--                  <div v-else-if="item.key==='testValue'">-->
<!--                    <el-input-->
<!--                      v-model="scope.row.testValue"-->
<!--                      size="medium"-->
<!--                      placeholder="请输入检测结果"-->
<!--                      @blur="_handleTestValueEdit(scope.row.id,scope.row.testValue)"-->
<!--                    />-->
<!--                  </div>-->
                  <div v-else-if="item.key==='progress'">
                    {{scope.row.progress.display}}
                  </div>
                  <div v-else>{{scope.row[item.key]}}</div>
                </template>
              </vxe-table-column>
            </PTVXETable>
          </Col>
        </Row>
      </div>
    </Modal>
  </div>
</template>
<script>
import { meterItem } from '../../api'
export default {
  components: {
    // FoodSampleGovernDetail,
    // CopyModal,
    // FoodSampleGovernLYEdits
  },
  data() {
    return {
      currentComponent: '',
      iconMsg: [
        {
          type: 'compose',
          id: 'meter-item-manage-edit-operation',
          name: '编辑'
        },
        {
          type: 'ios-copy',
          id: 'meter-item-manage-copy-operation',
          name: '复制',
          componentName: 'CopyModal'
        },
        {
          type: 'trash-a',
          id: 'meter-out-meter-item-manage-remove-operation',
          name: '删除'
        }
      ],
      btn: [],
      options: [
        {
          name: '检定'
        },
        {
          name: '校准'
        },
        {
          name: '外观检查'
        }
      ],
      formId: 'meterReviewSampleManageFormId',
      showModal: false,
      searchOpen: false,
      modalTitle: '检测项目管理',
      selectIds: [],
      selectData: [],
      getPage: {},
      pageColumns: [
        { title: '检定项目', key: 'name', width: 180 },
        { title: '比较符', key: 'compare', width: 100 },
        { title: '限量值', key: 'limitValue', width: 140 },
        { title: '检测值', key: 'testValue', width: 140 },
        { title: '单项判定', key: 'singleJudge', width: 140 },
        { title: '进度', key: 'progress', width: 110 }
      ],
      dateList: [],
      formObj: {
        sampleId: undefined,
        name: undefined,
        code: undefined,
        type: undefined
      }
    }
  },
  computed: {
    tableHeight: function() {
      return this.$tableHeight('tableModal')
    }
  },
  methods: {
    _dateChange(data) {
      this.formObj.ctimeBegin = data[0]
      this.formObj.ctimeEnd = data[1]
    },
    _btnClick(msg, componentName) {
      this.currentComponent = componentName
      this.$nextTick(function() {
        switch (msg) {
          case '完成':
            this._testEnd()
            break
          case '导入检测项目':
            this._importItem()
            break
          case '导入检测项目包':
            this._importItemPackage()
            break
          case '复制历史样品检测项目':
            this._copyHisItem()
            break
          case '删除':
            this._deleteSelected()
            break
        }
      })
    },
    _iconClick(res, data, componentName) {
      this.currentComponent = componentName
      this.$nextTick(function() {
        switch (res) {
          case '编辑':
            localStorage.setItem('type', data.type)
            if (data.type === 2) {
              this._editLY(data.id) // 粮油的编辑页
            } else {
              this._editModal(true, data.id)
            }
            break
          case '复制':
            this._copy(data.id, data.type)
            break
          case '删除':
            this._deleteById(data.id)
            break
          case '检测项目':
            this._itemDetail(data.id)
            break
        }
      })
    },
    _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 'iconClick':
          this._iconClick(data.name, data.rowData, data.componentName)
          break
        case 'changeSize':
          this._page()
          break
      }
    },
    _open(id) {
      this.formObj.sampleId = id
      this.showModal = true
      this._page()
    },

    _testEnd() {
      if (this.selectIds.length === 0) {
        this.$Message.success('请选择完成检测的项目')
        return false
      }
      this._testItemEnd(this.selectIds)
    },
    _testItemEnd: async function() {
      const result = await meterItem.testEnd({
        ids: this.selectIds,
        sampleId: this.formObj.sampleId
      })
      if (result) {
        await this._page()
      }
    },
    _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 meterItem.page(this.formObj)
      console.log('result', result)
      if (result) {
        this.getPage = result
        this.$refs.pageTable._hideLoading()
      }
    },
    _deleteByIds(ids, content) {
      this.$Modal.confirm({
        title: '提示',
        content: content || '确定删除该记录？',
        onOk: () => {
          this.$store.dispatch('FoodSample/deleteByIds', ids).then(() => {
            this._resultChange('删除成功!')
          })
        }
      })
    },
    _deleteById(id) {
      // 删除一条记录
      this._deleteByIds([id])
    },
    _deleteSelected() {
      // 批量删除
      const ids = this.selectIds
      if (ids.length === 0) {
        this.$Message.warning('请选择一条或多条数据！')
      } else {
        this._deleteByIds(ids, '确定删除 ' + ids.length + ' 条记录？')
      }
    },
    _detailModal(id) {
      this.currentComponent = 'FoodSampleGovernDetail'
      this.$nextTick(function() {
        this.$store.dispatch('FoodSample/getByGovernId', id).then(() => {
          this.$refs.refModal._open(this.$store.state.FoodSample.governModel)
        })
      })
    },
    _editModal(edit, id) {
      this.currentComponent = 'FoodSampleGovernEdit'
      this.$nextTick(function() {
        if (edit) {
          this.$store.dispatch('FoodSample/getByGovernId', id).then(() => {
            this.$refs.refModal._open(
              this.$store.state.FoodSample.governModel,
              this.contractId
            )
          })
        } else {
          this.$refs.refModal._open('', this.contractId)
        }
      })
    },
    _editLY(id) {
      // 粮油的编辑
      this.currentComponent = 'FoodSampleGovernLYEdit'
      this.$nextTick(function() {
        this.$store.dispatch('FoodSample/getByGovernId', id).then(() => {
          this.$refs.refModal._open(
            this.$store.state.FoodSample.governModel,
            this.contractId
          )
        })
      })
    },
    _search() {
      this._page()
    },
    _searchParams() {
      const data = this.$serialize('search-sample-govern')
      return this.$extend(data, this.pageParams)
    },
    _resultChange(msg) {
      if (this.$store.state.FoodSample.success) {
        this._page()
        this.$Message.success(msg)
      }
    },
    _copy(sampleId, type) {
      this.$refs.refModal._open(sampleId, type)
    },
    // 导入样品
    _importSample() {
      const data = {
        importUrl: '/food/v1/sample/government/import_' + this.contractId,
        downloadUrl: '/food/v1/excel/template/FoodSampleGovernment',
        title: '导入'
      }
      this.$refs.refModal._open(data)
    },
    // 导入检测项目
    _importItem() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this.$refs.refModal._open(this.selectIds, this.selectData[0])
      }
    },
    _subpackageSample() {
      if (this.selectData.length === 0) {
        this.$Message.warning('请至少选中一条样品进行分包！')
        return false
      } else {
        for (let i = 0; i < this.selectData.length; i++) {
          if (this.selectData[i].jobOut === 1) {
            this.$Message.warning(
              '样品编号为' +
                this.selectData[i].code +
                '已经分包了，请选择未分包的样品！'
            )
            return false
          }
        }
        this._subpackage(this.selectIds)
      }
    },

    _importItemPackage() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this.$refs.refModal._open(this.selectIds, 'batch-rel-package-item')
      }
    },
    _copyHisItem() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this.$refs.refModal._open(this.selectIds)
      }
    },
    _itemDetail(id) {
      this.$refs.foodItem._open(id)
    },
    _operationRecord(id) {
      // 操作日志
      this.$refs.recordModal._open(id)
    },
    // 单个填写检测值
    _handleTestValueEdit: async function(id, testValue) {
      if (testValue !== '' && undefined !== testValue) {
        const data = {}
        data.itemIds = id
        data.testValue = testValue
        const result = await meterItem.testValue(data)
        if (result) {
          this.$Message.success('保存成功')
          await this._page()
        } else {
          this.$Message.error('保存失败')
        }
      }
    }
  }
}
</script>
