<template>
  <div>
    <div>
      <!--内容-->
      <Row>
        <!--查询-->
        <Col span="24" style="padding-bottom: 5px">
          <Form id="search-wait" :label-width="100" 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.sampleCode" name="sampleCode" placeholder="请输入试样编号" clearable></Input>
            </Form-item>
            <Form-item label="是否有试验项目:" class="search-item">
              <Select v-model="formObj.haveExp" clearable name="groupId" style="width:150px" placeholder="请选择检测科室">
                <Option v-for="(item,index) in itemData" :value="item.value" :key="index">{{item.name}}</Option>
              </Select>
            </Form-item>
            <Form-item class="search-btn">
              <Button @click="_formSearch" type="primary">搜索</Button>
            </Form-item>
          </Form>
        </Col>
        <Col span="24">
          <btn-list :msg="btn" :open="searchOpen" @on-result-change="_btnClick" :show-search-btn="true" class="contHide">
          </btn-list>
        </Col>
        <Col span="24">
          <PTVXETableHeight
            ref="pageTable"
            :tableHeight="tableHeight"
            @on-result-change="_tableResultChange"
            :getPage="getPage"
            :iconMsg="iconMsg"
            select-data>
            <vxe-table-column
              v-for="item in pageColumns"
              :key="item.key"
              :field="item.key"
              :title="item.title"
              :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.key ==='shape'">{{scope.row['shape']}} {{scope.row['shapeRemark']}}</div>
                <div v-else-if="item.date">
                  {{scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd'):''}}
                </div>
                <div v-else>{{scope.row[item.key]}}</div>
              </template>
            </vxe-table-column>
          </PTVXETableHeight>
        </Col>
      </Row>
    </div>
    <!--选择领样人-->
    <SampleReceiveModal ref="locationModal" @on-result-change="_page()"></SampleReceiveModal>
    <SoilSampleItemManage ref="sampleItemManage" @on-result-change="_page"></SoilSampleItemManage>
    <KeepAdress ref="keepAdressModal" @on-result-change="_page"></KeepAdress>
  </div>
</template>
<script>
import { soilEntrust } from '../../../../api'
import SampleReceiveModal from '../SampleReceiveModal'
import SoilSampleItemManage from './SoilSampleItemManage'
import KeepAdress from './KeepAdress'
export default {
  components: { SampleReceiveModal, SoilSampleItemManage, KeepAdress },
  data() {
    return {
      btn: [
        { type: 'primary', id: '', name: '收样室收样' },
        { type: 'primary', id: '', name: '样品留存' }
      ],
      selectIds: [],
      getPage: {},
      itemData: [
        {
          name: '是',
          value: 1
        },
        {
          name: '否',
          value: 0
        }
      ],
      pageColumns: [
        { title: '试样编号', key: 'sampleCode', width: 120, fixed: 'left' },
        { title: '试样深度', key: 'sampleDepth', width: 100 },
        { title: '现场编号', key: 'siteNo', width: 100 },
        { title: '试验项目', key: 'experimentNames', width: 220 },
        { title: '土质描述', key: 'sampleDescribe', width: 205 },
        { title: '样品包装类型', key: 'samplePack', width: 120 },
        { title: '备注', key: 'remark', width: 210 }
      ],
      iconMsg: [{ type: 'ios-list', id: '', name: '试验项目' }],
      type: '',
      contractId: '', // 合同id
      selectData: [],
      currentComponent: '',
      formObj: {
        samplingNum: '',
        name: '',
        num: '',
        detectType: '',
        standard: '',
        samplingLinkList: [],
        haveExp: undefined
      },
      stdList: [],
      sampleLinkList: [
        { value: 0, name: '食品生产' },
        { value: 1, name: '食品流通' },
        { value: 2, name: '餐饮服务' },
        { value: 3, name: '食用农产品' },
        { value: 4, name: '生产' },
        { value: 5, name: '流通' },
        { value: 6, name: '餐饮' }
      ],
      searchOpen: true,
      acceptSelectUserValue: ''
    }
  },
  computed: {
    tableHeight: function() {
      if (this.searchOpen) {
      } else {
      }
      return this.$tableHeight('tableModal')
    }
  },
  mounted() {
    // 样品接收是否选择人员
    // this.acceptSelectUserValue = localStorage.getItem('acceptSelectUserValue')
    // this._getStdList()
  },
  methods: {
    _userResult(data, msg) {
      const sendData = {
        ids: this.selectIds.join(','),
        contractId: this.contractId
      }
      if (data) {
        sendData.person = data.realname
        sendData.personId = data.userId
      }
      switch (msg) {
        case 'sampleReceiveSendMan':
          // 接收并发放
          this.$store
            .dispatch('FoodSample/sampleReceiveSend', sendData)
            .then(() => {
              this._resultChange('接收发放成功')
            })
          break
        case 'sampleMan':
          // 扫码接收并发放
          this.$refs.refModal._open('扫码接收发放', data)
          break
      }
    },
    _selectSampleLink(data) {
      console.log(data)
    },
    // 组件返回值
    _componentResult(data, msg) {
      switch (this.currentComponent) {
        case 'SelectPrinter':
          this._printerResult(data)
          break
        case 'ReceiveScan':
          // 扫码接收
          this._searchTop()
          break
        default:
          this._search()
      }
    },
    _detailModal(id) {
      // 查看
      if (this.type === 0) {
        // 政府
        this.currentComponent = 'FoodSampleCompanyDetail'
        this.$store.dispatch('FoodSample/getByCompanyId', id).then(() => {
          this.$nextTick(() => {
            this.$refs.refModal._open(this.$store.state.FoodSample.companyModel)
          })
        })
      } else {
        this.currentComponent = 'FoodSampleGovernDetail'
        this.$store.dispatch('FoodSample/getByGovernId', id).then(() => {
          this.$nextTick(() => {
            this.$refs.refModal._open(this.$store.state.FoodSample.governModel)
          })
        })
      }
    },
    _open(contractId, type) {
      console.log('待接收样品')
      this.formObj = this.$resetFields(this.formObj)
      $('input[name=contractId]').val(contractId)
      this.entrustId = contractId
      this.type = type
      this.selectIds = []
      this.saveWayList = []
      this.saveWayString = ''
      this.$nextTick(() => {
        this._page()
      })
    },
    _page: async function() {
      Object.assign(this.formObj, this.$refs.pageTable._searchParams())
      console.log('this.formObj', this.formObj)
      this.formObj.entrustId = this.entrustId
      const result = await soilEntrust.pageReceive(
        this.$serializeForm(this.formObj)
      )
      if (result) {
        this.$refs.pageTable._hideLoading()
        this.getPage = result
      }
    },
    _formSearch() {
      this.$refs.pageTable._pageChange(1)
    },
    _iconClick(res, data, currentComponent) {
      this.currentComponent = currentComponent
      this.$nextTick(() => {
        switch (res) {
          case '编辑':
            this._editModal(true, data)
            break
          case '试验项目':
            this._itemManage(data.id)
            break
          case '复制':
            this._copySample(data)
            break
          case '操作日志':
            this.$refs.refModal._open(data.id)
            break
          case '删除':
            this._deleteById(data.id)
            break
          case '附件':
            this.$refs.refModal._open(data.id, 'sampleId')
            break
        }
      })
    },
    _itemManage(data) {
      // 管理检测项目
      if (this.recordHis) {
        this.$refs.sampleItemManage._openRecord(data)
      } else {
        this.$refs.sampleItemManage._open(data)
      }
    },
    _btnClick(msg, currentComponent) {
      this.currentComponent = currentComponent
      this.$nextTick(() => {
        switch (msg) {
          case '添加':
            this._editModal(false)
            break
          case '接收并发放':
            this._submitSend()
            break
          case '扫码接收':
            this.$refs.refModal._open()
            break
          case '扫码接收并发放':
            if (this.acceptSelectUserValue === '是') {
              // 扫码接收并发放根据字典是否选人
              this.$refs.userModal._open('sampleMan', '请选择领样人')
            } else {
              this.$refs.refModal._open('扫码接收发放')
            }
            break
          case '导入检测项目':
            this._importItem()
            break
          case '导入检测项目包':
            this._importItemPackage()
            break
          case '复制历史样品检测项目':
            this._copyHisItem()
            break
          case '收样室收样':
            this._sampleReceive(this.selectIds)
            break
          case '样品留存':
            this._sampleKeep(this.selectIds)
            break
          case '打印标签':
            this._selectPrinter('print-label')
            break
          case '自定义打印':
            if (this.selectData.length === 0) {
              this.$Message.warning('请至少选择一条数据')
            } else {
              this._cusTomePrint()
            }
            break
          case 'search':
            this.searchOpen = !this.searchOpen
            break
        }
      })
    },
    // 1.自定义打印，除检样、备样、留样 增加制备标签，需要单独的查询制备标签的数据，
    // 2.样品接收位置的制备用制备的的接口，将当前的保存方式置空，打印出来手动填写
    _cusTomePrint() {
      this.$store
        .dispatch('FoodSample/preparationButton', {
          sampleIds: this.selectIds.join(',')
        })
        .then(() => {
          const result = this.$store.state.FoodSample.list
          for (let i = 0; i < result.length; i++) {
            // 样品制备保存方式
            result[i].saveWay = ''
          }
          // 样品的数据和制备样品的数据
          this.$refs.refModal._open(this.selectData, result)
        })
    },
    // 接收并发放
    _submitSend() {
      if (this.selectIds.length === 0) {
        this.$msgTip('warning', '请至少选择一条数据！')
      } else {
        const data = {
          ids: this.selectIds.join(',')
        }
        // 判断接收发放是否选人
        if (this.acceptSelectUserValue === '是') {
          this.$store
            .dispatch('FoodSample/submitReceiveSendCheck', data)
            .then(() => {
              const result = this.$store.state.FoodSample.success
              if (result) {
                // 验证成功
                this.$refs.userModal._open(
                  'sampleReceiveSendMan',
                  '请选择领样人'
                )
              }
            })
        } else {
          this.$store
            .dispatch('FoodSample/sampleReceiveSend', data)
            .then(() => {
              this._resultChange('接收发放成功')
            })
        }
      }
    },
    _resultChange(msg) {
      if (this.$store.state.FoodSample.success) {
        this._page()
        this.$Message.success(msg)
        this.selectIds = []
      }
    },

    _exportReceiveRecord() {
      // 导出交接记录
      const ids = this.selectIds
      if (ids.length === 0) {
        this.$Message.warning('请选择数据进行导出')
      } else {
        // eslint-disable-next-line no-undef
        http.open(
          '/food/report/excel/sheet?_u=db样品来源.report.xml&ids=' + ids
        )
      }
    },

    _deleteById(id) {
      // 删除一条记录
      this.$Modal.confirm({
        title: '提示',
        content: '确定删除该记录？',
        onOk: () => {
          this.$store.dispatch('FoodSample/deleteByIds', id).then(() => {
            if (this.$store.state.FoodSample.success) {
              this._page()
              this.$Message.success('删除成功！')
            }
          })
        }
      })
    },
    // 添加与编辑
    _editModal(edit, data) {
      if (edit) {
        // 编辑
        if (data.type === 1) {
          // 政府
          this.currentComponent = 'SampleGovernEdit'
          this.$store.dispatch('FoodSample/getByGovernId', data.id).then(() => {
            this.$nextTick(() => {
              this.$refs.refModal._open(
                this.$store.state.FoodSample.governModel,
                this.contractId,
                'receive-his-wait'
              )
            })
          })
        } else if (data.type === 2) {
          this.currentComponent = 'FoodSampleGovernLYEdit'
          this.$nextTick(function() {
            this.$store
              .dispatch('FoodSample/getByGovernId', data.id)
              .then(() => {
                this.$refs.refModal._open(
                  this.$store.state.FoodSample.governModel,
                  this.contractId,
                  'receive-his-wait'
                )
              })
          })
        } else {
          this.currentComponent = 'CompanySampleEdit'
          this.$store
            .dispatch('FoodSample/getByCompanyId', data.id)
            .then(() => {
              this.$nextTick(() => {
                this.$refs.refModal._open(
                  this.$store.state.FoodSample.companyModel,
                  this.contractId,
                  'receive-his-wait'
                )
              })
            })
        }
      } else {
        // 添加
        if (this.type === 0) {
          // 企业
          this.currentComponent = 'CompanySampleEdit'
        } else {
          // 政府和粮油
          this.currentComponent = 'SampleGovernEdit'
        }
        this.$nextTick(() => {
          // receive 标识，表示是样品接收的添加页面与其他普通样品的添加页面不同
          this.$refs.refModal._open('', this.contractId, 'receive-his-wait')
        })
      }
    },
    // 复制样品
    _copySample(data) {
      this.$Modal.confirm({
        title: '提示',
        content: '确定要复制该样品信息？',
        onOk: () => {
          if (data.type === 1) {
            // 政府
            this.currentComponent = 'SampleGovernEdit'
            this.$store
              .dispatch('FoodSample/getByGovernId', data.id)
              .then(() => {
                this.$nextTick(() => {
                  this.$refs.refModal._openCopyAll(
                    this.$store.state.FoodSample.governModel,
                    'receive-his-wait-copy'
                  )
                })
              })
          } else if (data.type === 2) {
            this.currentComponent = 'FoodSampleGovernLYEdit'
            this.$store
              .dispatch('FoodSample/getByGovernId', data.id)
              .then(() => {
                this.$nextTick(() => {
                  this.$refs.refModal._openCopyAll(
                    this.$store.state.FoodSample.governModel,
                    'receive-his-wait-copy'
                  )
                })
              })
          } else {
            this.currentComponent = 'CompanySampleEdit'
            this.$store
              .dispatch('FoodSample/getByCompanyId', data.id)
              .then(() => {
                this.$nextTick(() => {
                  this.$refs.refModal._openCopyAll(
                    this.$store.state.FoodSample.companyModel,
                    'receive-his-wait-copy'
                  )
                })
              })
          }
        }
      })
    },
    _search() {
      this._page()
    },
    // 刷新上级页面
    _searchTop() {
      this._page()
      this.$emit('on-result-change')
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'page':
          this.getPage = this.$store.state.FoodSample.page
          break
        case 'selectData':
          this.selectData = data
          this.selectIds = []
          for (let i = 0; i < data.length; i++) {
            this.selectIds.push(data[i].id)
          }
          break
        case 'iconClick':
          this._iconClick(data.name, data.rowData, data.componentName)
          break
        case 'changeSize':
          this._page()
          break
      }
    },
    _sampleKeep(id) {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        const ids = id.join(',')
        this.$refs.keepAdressModal._open(ids)
      }
    },
    // 样品接收
    _sampleReceive(id) {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        const ids = id.join(',')
        this.$refs.locationModal._open(ids)
        // const tempData = {
        //   ids: this.selectIds.join(',')
        // }
        // this.$Modal.confirm({
        //   title: '提示',
        //   content: '确定要接收这 ' + this.selectIds.length + ' 条数据？',
        //   onOk: () => {
        //     console.log(tempData)
        //   }
        // })
      }
    },

    // 导入检测项目包
    _importItemPackage() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this.$nextTick(() => {
          this.$refs.refModal._open(this.selectIds)
        })
      }
    },
    // 导入检测项目
    _importItem() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this.$nextTick(() => {
          this.$refs.refModal._open(this.selectIds, this.selectData[0])
        })
      }
    },
    _copyHisItem() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this.$nextTick(() => {
          this.$refs.refModal._open(this.selectIds)
        })
      }
    },
    // 选择打印机
    _selectPrinter(msg) {
      if (this.selectData.length === 0) {
        this.$Message.warning('请至少选择一条数据')
      } else {
        this.$refs.refModal._open(msg)
      }
    },
    // 选择完打印机之后
    _printerResult(data) {
      // printModal  不能使用动态组件，否则第二次打不开，原因未知
      switch (data.type) {
        // 打印标签--直接打印
        case 'print-label':
          this.$refs.printModal._printOpen(this.selectData, data.printerVal)
          break
      }
    },
    _stdResult(msg, data) {
      switch (msg) {
        case 'select':
          this.formObj.standard = data
          break
        case 'query':
          this.formObj.standard = data
          this._getStdList(data)
          break
        case 'focus':
          this._getStdList()
          break
      }
    },
    // 查询执行标准
    _getStdList(data) {
      const obj = Object.assign({}, this.$serialize('search-wait'))
      if (data) {
        obj.standard = data
      }
      this.$store.dispatch('FoodSample/listReceiveStandard', obj).then(() => {
        this.stdList = this.$store.state.FoodSample.list
      })
    }
  }
}
</script>
