<template>
  <div>
    <!--内容-->
    <div class="layout-content-padding">
      <div class="layout-content-main">
        <Row>
          <!--查询-->
          <Col span="24">
            <Form id="search-form-rel-sample" :label-width="80" v-show="searchOpen" inline onsubmit="return false">
              <label class="label-sign"></label>
              <Form-item class="search-item" label="试样编号:">
                <Input @on-enter="_formSearch" v-model="formObj.sampleCode" name="sampleCode" placeholder="请输入样品编号" clearable></Input>
              </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" :showSearchBtn="true"
                     class="contHide">
            </btn-list>

          </Col>
          <!-- 表格 -->
          <Col span="24">
            <PTVXETable
              ref="pageTable"
              :tableHeight="tableHeight"
              @on-result-change="_tableResultChange"
              :getPage="getPage"
              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.contractId,scope.row.type)">{{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.sampleDetail"><a @click.stop="_sampleDetailModal(scope.row.id,scope.row.type)">{{scope.row[item.key]}}</a>
                  </div>
                  <div v-else>{{scope.row[item.key]}}</div>
                </template>
              </vxe-table-column>
            </PTVXETable>
          </Col>
        </Row>
      </div>
    </div>
    <!--组件加载-->
    <!--打印（可填打印数量）-->
    <!--选择领样人-->
    <UserInfo ref="userModal" @on-result-change="_userResult"></UserInfo>
    <TakeByEwm ref="ewmModal" @on-result-change="_page"></TakeByEwm>

  </div>
</template>
<script>
import http from '../../../api/http'
import UserInfo from '../../../components/user-info-single/assignPerson'
import { soilEntrust, soilSample } from '../../../api'
import TakeByEwm from './TakeByEwm'
export default {
  components: {
    UserInfo,
    TakeByEwm
  },
  data() {
    return {
      formObj: { num: undefined, name: undefined },
      iconMsgDis: [],
      iconMsg: [
        {
          type: 'md-create',
          id: '',
          name: '编辑'
        },
        { type: 'md-cloud', id: '', name: '附件' },
        { type: 'md-trash', id: '', name: '删除' },
        {
          type: 'ios-clock',
          id: '',
          name: '操作日志'
        }
      ],
      // 操作列
      sampleFile: {
        type: 'cloud',
        id: '',
        name: '样品附件',
        componentName: 'FileManage'
      },
      sampleFileDis: {
        type: 'cloud',
        id: '',
        name: '样品附件',
        disabled: true
      },
      edit: {
        type: 'compose',
        id: 'rel-sample-receive-edit-sample',
        name: '编辑'
      },
      del: {
        type: 'trash-a',
        id: 'rel-sample-receive-del-sample',
        name: '删除'
      },
      record: {
        type: 'ios-clock',
        id: '',
        name: '操作日志',
        componentName: 'FoodSampleRecord'
      },
      getPage: {},
      pageColumns: [
        { title: '试样编号', key: 'sampleCode', width: 130 },
        { title: '试样深度', key: 'sampleDepth', width: 130 },
        { title: '检测科室', key: 'groupName', width: 160 },
        { title: '保存容器', key: 'keepContainer', width: 160 },
        { title: '保存方式', key: 'keepWay', width: 160 },
        { title: '制备方式', key: 'prepareWay', width: 160 },
        { title: '制备人', key: 'preparer', width: 130 },
        { title: '制备数量', key: 'quantity', width: 130 },
        { title: '单位', key: 'unit', width: 130 }
      ],
      searchOpen: false,
      btn: [
        { type: 'primary', id: '', name: '领样', componentName: '' },
        { type: 'primary', id: '', name: '扫码领样', componentName: '' }
      ],
      selectIds: [],
      selectData: [],
      currentComponent: '',
      printerVal: '', // 选择的打印机
      standard: '',
      stdList: [],
      acceptSelectUserValue: ''
    }
  },
  computed: {
    tableHeight: function() {
      if (this.searchOpen) {
        return this.$tableHeight('', 340)
      } else {
        return this.$tableHeight('tabNoSearch')
      }
    }
  },
  mounted() {
    // // 获取当前的执行标准下拉项
    // this._getStdList()
  },
  methods: {
    // 接收的返回保存
    _userResult(data, msg) {
      const sendData = {
        ids: this.selectIds.join(',')
      }
      if (data) {
        sendData.person = data.realname
        sendData.personId = data.userId
      }
      switch (msg) {
        case 'relReceiveSendScanMan':
          // 扫码接收并发放
          this.$refs.refModal._open('扫码接收发放', data)
          break
      }
    },
    // 抽样日期
    _makeDateChange(data) {
      $('input[name=samplingDateBegin]').val(data[0])
      $('input[name=samplingDateEnd]').val(data[1])
    },
    // 组件返回值
    _componentResult(data, msg) {
      switch (this.currentComponent) {
        case 'SelectPrinter':
          this._printerResult(data)
          break
        default:
          this._page()
      }
    },
    _btnClick(msg, currentComponent, formTypeObj) {
      this.currentComponent = currentComponent
      this.$nextTick(() => {
        switch (msg) {
          case 'search':
            this.searchOpen = !this.searchOpen
            break
          case '领样':
            this._sampleTake()
            break
          case '扫码领样':
            this._ewmTake()
            break
          default:
            this._btnOption(msg, formTypeObj)
        }
      })
    },
    _ewmTake() {
      this.$refs.ewmModal._open()
    },
    // btn操作
    _btnOption(msg, formTypeObj) {
      switch (msg) {
        case '扫码接收并发放':
          // 根据字典判断是否选择人员
          if (this.acceptSelectUserValue === '是') {
            this.$refs.userModal._open('relReceiveSendScanMan', '请选择领样人')
          } else {
            this.$refs.refModal._open('扫码接收发放')
          }
          break
        case '接收并发放':
          this._submitSend()
          break
        case '添加':
          if (formTypeObj.uri === 'DLTB-contract-reg') {
            this.currentComponent = 'FoodContractCompanyEditByDLTB'
          } else if (formTypeObj.uri === 'HES-company-contract-reg') {
            this.currentComponent = 'FoodContractCompanyEditByHES'
          } else {
            this.currentComponent = 'FoodContractCompanyEdit'
          }
          this.$nextTick(() => {
            this.$refs.refModal._openReceive()
          })
          break
        case '导入检测项目':
          this._importItem()
          break
        case '导入检测项目包':
          this._importItemPackage()
          break
        case '复制历史样品检测项目':
          this._copyHisItem()
          break
        case '删除':
          this._deleteSelected()
          break
        case '打印标签':
          this._selectPrinter('print-label')
          break
        case '自定义打印':
          if (this.selectData.length === 0) {
            this.$Message.warning('请至少选择一条样品信息')
          } else {
            this._cusTomePrint()
          }
          break
      }
    },
    _sampleTake() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据')
      } else {
        this.$Modal.confirm({
          title: '提示',
          content: '确认领样',
          onOk: () => {
            this._confirmTake(this.selectIds.join(','))
          }
        })
      }
    },
    _confirmTake: async function(ids) {
      const result = await soilSample.takeSample({ ids: ids })
      if (result) {
        this._resultChange('领样成功')
      }
    },
    // 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('relReceiveSendMan', '请选择领样人')
              }
            })
        } else {
          this.$store
            .dispatch('FoodSample/sampleReceiveSend', data)
            .then(() => {
              this._resultSampleChange('接收并发放成功')
            })
        }
      }
    },
    _exportReceiveRecord() {
      // 导出交接记录
      const ids = this.selectIds
      if (ids.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
        /* this.$Modal.confirm({
            title: '提示',
            content: '确定导出所有记录？',
            onOk: () => {
              http.open('/food/report/excel/sheet?_u=db样品来源.report.xml&ids=' + ids);
            }
          }); */
      } else {
        http.open(
          '/food/report/excel/sheet?_u=db样品来源.report.xml&ids=' + ids
        )
      }
    },

    // 单个删除
    _deleteById(id) {
      this._deleteByIds([id], '确定删除该条记录？')
    },
    _deleteByIds(ids, content) {
      this.$Modal.confirm({
        title: '提示',
        content: content || '确定删除该记录？',
        onOk: () => {
          this.$store.dispatch('FoodSample/deleteByIds', ids).then(() => {
            this._resultSampleChange('删除成功!')
          })
        }
      })
    },
    _deleteSelected() {
      // 批量删除
      const ids = this.selectIds
      if (ids.length === 0) {
        this.$Message.warning('请选择一条或多条数据！')
      } else {
        this._deleteByIds(ids, '确定删除 ' + ids.length + ' 条记录？')
      }
    },
    // 导入检测项目包
    _importItemPackage() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this.$refs.refModal._open(this.selectIds)
      }
    },
    // 导入检测项目
    _importItem() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this.$refs.refModal._open(this.selectIds, this.selectData[0])
      }
    },
    _copyHisItem() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this.$refs.refModal._open(this.selectIds)
      }
    },
    _iconClick(res, data, currentComponent, rowIndex, obj) {
      this.currentComponent = currentComponent
      this.$nextTick(() => {
        switch (res) {
          case '编辑':
            if (data.type === 0) {
              // 企业--编辑的是委托和样品信息

              this.$store
                .dispatch('SysForm/getByBtnCode', obj.btnId)
                .then(() => {
                  const result = this.$store.state.SysForm.list
                  if (result.length === 0) {
                    this.$store
                      .dispatch('FoodSample/companyPage', {
                        contractId: data.contractId
                      })
                      .then(() => {
                        const num = this.$store.state.FoodSample.companyPage
                          .total
                        if (num <= 1) {
                          // 无配置表单 委托的编辑界面
                          this.currentComponent = 'FoodContractCompanyEdit'
                          this.$nextTick(() => {
                            this.$store
                              .dispatch('FoodContract/getBySampleId', data.id)
                              .then(() => {
                                this.$refs.refModal._openReceive(
                                  this.$store.state.FoodContract.model
                                )
                              })
                          })
                        } else {
                          // 样品的编辑界面
                          this.currentComponent = 'FoodSampleCompanyEdit'
                          this.$nextTick(() => {
                            this.$store
                              .dispatch('FoodSample/getByCompanyId', data.id)
                              .then(() => {
                                this.$refs.refModal._open(
                                  this.$store.state.FoodSample.companyModel,
                                  data.contractId,
                                  'receive-his-wait'
                                )
                              })
                          })
                        }
                      })
                  } else if (
                    result.length === 1 &&
                    result[0].uri === 'DLTB-contract-reg'
                  ) {
                    // 只有一个配置表单(不需要选择)
                    this.currentComponent = 'FoodContractCompanyEditByDLTB'
                    this.$nextTick(() => {
                      this.$store
                        .dispatch('FoodContract/getBySampleId', data.id)
                        .then(() => {
                          this.$refs.refModal._openReceive(
                            this.$store.state.FoodContract.model
                          )
                        })
                    })
                  } else if (
                    result.length === 1 &&
                    result[0].uri === 'HES-company-contract-reg'
                  ) {
                    // 只有一个配置表单(不需要选择)
                    this.currentComponent = 'FoodContractCompanyEditByHES'
                    this.$nextTick(() => {
                      this.$store
                        .dispatch('FoodContract/getBySampleId', data.id)
                        .then(() => {
                          this.$refs.refModal._openReceive(
                            this.$store.state.FoodContract.model
                          )
                        })
                    })
                  }
                })
            } else if (data.type === 1) {
              // 政府--只是编辑样品信息
              this.currentComponent = 'FoodSampleGovernEdit'
              this.$nextTick(() => {
                this.$store
                  .dispatch('FoodSample/getByGovernId', data.id)
                  .then(() => {
                    this.$refs.refModal._open(
                      this.$store.state.FoodSample.governModel,
                      data.contractId,
                      'receive-his-wait'
                    )
                  })
              })
            } else {
              // 粮油--只是编辑样品信息
              this.currentComponent = 'FoodSampleGovernLYEdit'
              this.$nextTick(() => {
                this.$store
                  .dispatch('FoodSample/getByGovernId', data.id)
                  .then(() => {
                    this.$refs.refModal._open(
                      this.$store.state.FoodSample.governModel,
                      data.contractId,
                      'receive-his-wait'
                    )
                  })
              })
            }
            break
          case '删除':
            this._deleteById(data.id)
            break
          case '复制':
            if (data.type === 0) {
              // 企业--复制的是委托和样品信息

              this.$store
                .dispatch('SysForm/getByBtnCode', obj.btnId)
                .then(() => {
                  const result = this.$store.state.SysForm.list
                  if (result.length === 0) {
                    // 无配置表单
                    this.currentComponent = 'FoodContractCompanyEdit'
                    this.$nextTick(() => {
                      this.$store
                        .dispatch('FoodContract/getBySampleId', data.id)
                        .then(() => {
                          this.$refs.refModal._openReceiveCopy(
                            this.$store.state.FoodContract.model
                          )
                        })
                    })
                  } else if (
                    result.length === 1 &&
                    result[0].uri === 'DLTB-contract-reg'
                  ) {
                    // 只有一个配置表单(不需要选择)
                    this.currentComponent = 'FoodContractCompanyEditByDLTB'
                    this.$nextTick(() => {
                      this.$store
                        .dispatch('FoodContract/getBySampleId', data.id)
                        .then(() => {
                          this.$refs.refModal._openReceiveCopy(
                            this.$store.state.FoodContract.model
                          )
                        })
                    })
                  } else if (
                    result.length === 1 &&
                    result[0].uri === 'HES-company-contract-reg'
                  ) {
                    // 只有一个配置表单(不需要选择)
                    this.currentComponent = 'FoodContractCompanyEditByHES'
                    this.$nextTick(() => {
                      this.$store
                        .dispatch('FoodContract/getBySampleId', data.id)
                        .then(() => {
                          this.$refs.refModal._openReceiveCopy(
                            this.$store.state.FoodContract.model
                          )
                        })
                    })
                  }
                })
            } else if (data.type === 1) {
              // 政府--只是复制样品信息
              this.currentComponent = 'FoodSampleGovernEdit'
              this.$nextTick(() => {
                this.$store
                  .dispatch('FoodSample/getByGovernId', data.id)
                  .then(() => {
                    this.$refs.refModal._openCopyAll(
                      this.$store.state.FoodSample.governModel,
                      'receive-his-wait-copy'
                    )
                  })
              })
            } else {
              // 粮油--只是复制样品信息
              this.currentComponent = 'FoodSampleGovernLYEdit'
              this.$nextTick(() => {
                this.$store
                  .dispatch('FoodSample/getByGovernId', data.id)
                  .then(() => {
                    this.$refs.refModal._openCopyAll(
                      this.$store.state.FoodSample.governModel,
                      'receive-his-wait-copy'
                    )
                  })
              })
            }
            break
          case '操作日志':
            this._operationRecord(data.id)
            break
          case '导出委托协议':
            // this.$Modal.confirm({
            //   title: '提示',
            //   content: '确认要下载委托单？',
            //   onOk: () => {
            //     http.open('/food/v1/sample/export_sample_form?id=' + data.id);
            //   }
            // });
            this._downContractForm(data.id)
            break
          case '样品附件':
            this._upload(data.id)
            break
        }
      })
    },
    _downContractForm(id) {
      this.$store
        .dispatch(
          'ReportExport/getById',
          'food-sample-receive-sample-download-contract'
        )
        .then(() => {
          if (this.$store.state.ReportExport.model) {
            if (this.$store.state.ReportExport.model.indexOf('?') !== -1) {
              window.open(
                this.$store.state.ReportExport.model + '&sampleId=' + id,
                '_blank'
              )
            } else {
              window.open(
                this.$store.state.ReportExport.model + '?sampleId=' + id,
                '_blank'
              )
            }
          }
        })
    },
    _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 'changeSize':
          this._page()
          break
      }
    },
    _formSearch() {
      this.$refs.pageTable._pageChange(1)
    },
    _page: async function() {
      Object.assign(this.formObj, this.$refs.pageTable._searchParams())
      console.log(this.$refs.pageTable._searchParams())
      console.log('this.formObj', this.formObj)
      const result = await soilEntrust.pageTake(
        this.$serializeForm(this.formObj)
      )
      if (result) {
        this.$refs.pageTable._hideLoading()
        this.getPage = result
      }
    },
    // 查看委托
    _detailModal(contractId, type) {
      this.$store.dispatch('FoodContract/getById', contractId).then(() => {
        if (type === 0) {
          // 企业委托 ’0‘
          this.currentComponent = 'FoodContractCompanyDetail'
        } else {
          // 政府委托 ’1‘
          this.currentComponent = 'FoodContractGovernDetail'
        }
        this.$nextTick(() => {
          this.$refs.refModal._open(this.$store.state.FoodContract.model)
        })
      })
    },
    // 查看样品
    _sampleDetailModal(id, type) {
      if (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)
          })
        })
      }
    },
    _editModal(id, type) {
      this.$refs.refModal._open(id, type)
    },
    _search() {
      this._page()
    },
    _operationRecord(id) {
      // 操作日志
      this.$refs.refModal._open(id)
    },
    _resultChange(msg) {
      this._page()
      this.$Message.success(msg)
      this.selectIds = []
    },
    _resultSampleChange(msg) {
      if (this.$store.state.FoodSample.success) {
        this._page()
        this.$Message.success(msg)
        this.selectIds = []
      }
    },
    _upload(id) {
      // 上传文件
      this.$refs.refModal._open(id, 'sampleId')
    },
    // 选择完打印机之后
    _printerResult(data) {
      // printModal  不能使用动态组件，否则第二次打不开，原因未知
      switch (data.type) {
        // 打印标签--直接打印
        case 'print-label':
          this.$refs.printModal._printOpen(this.selectData, data.printerVal)
          break
      }
    },
    // 选择打印机
    _selectPrinter(msg) {
      if (this.selectData.length === 0) {
        this.$Message.warning('请至少选择一条数据')
      } else {
        this.$refs.refModal._open(msg)
      }
    },
    _stdResult(msg, data) {
      switch (msg) {
        case 'select':
          this.standard = data
          break
        case 'query':
          this.standard = data
          this._getStdList(data)
          break
        case 'focus':
          this._getStdList()
          break
      }
    },
    // 查询执行标准
    _getStdList(data) {
      const obj = Object.assign({}, this.$serialize('search-form-rel-sample'))
      if (data) {
        obj.standard = data
      }
      this.$store.dispatch('FoodSample/listReceiveStandard', obj).then(() => {
        this.stdList = this.$store.state.FoodSample.list
      })
    }
  }
}
</script>
