<template>
  <div>
    <div>
      <!--内容-->
      <Row>
        <!--查询-->
        <Col span="24" style="margin-bottom: 10px">
          <Form id="search-send" :label-width="80" 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.name" name="name" placeholder="请输入样品名称" clearable></Input>
            </Form-item>
            <Form-item label="样品编号:" class="search-item">
              <Input @on-enter="_formSearch" v-model="formObj.num" name="num" placeholder="请输入样品编号" clearable></Input>
              <input name="contractId" type="hidden">
            </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">

            <!--<template slot="processTask">-->
            <!--<div class="fr process-task">-->
            <!--<Button @click="_exportReceiveRecord">导出交接记录</Button>-->
            <!--</div>-->
            <!--</template>-->

          </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>{{scope.row[item.key]}}</div>
              </template>
            </vxe-table-column>
          </PTVXETable>
        </Col>
      </Row>
    </div>
    <!--组件加载-->
  </div>
</template>
<script>
import { soilEntrust } from '../../../../api'

export default {
  components: {},
  data() {
    return {
      btn: [
        {
          id: 'ZBC',
          type: 'primary',
          name: '出库',
          componentName: 'OutStorage'
        }
      ],
      selectIds: [],
      getPage: {},
      pageColumns: [
        {
          title: '样品编号',
          key: 'num',
          width: 180,
          detail: true,
          fixed: 'left'
        },
        { title: '样品名称', key: 'name', width: 160, fixed: 'left' },
        { title: '执行标准', key: 'standard', width: 160 },
        { title: '大类', key: 'firstClass', width: 130 },
        { title: '细类', key: 'detectType', width: 200 },
        { title: '抽样单编号', key: 'samplingNum', width: 200 },
        { title: '状态', key: 'status', width: 120, status: true },
        { title: '检测项目', key: 'itemName', width: 160 },
        { title: '规格型号', key: 'specification', width: 160 },
        { title: '质量等级', key: 'qualityGrade', width: 160 },
        { title: '样品数量', key: 'quantity', width: 100 },
        { title: '单位', key: 'unit', width: 90 },
        { title: '抽样环节', key: 'samplingLink', width: 160 },
        { title: '备样数量', key: 'backupQuanity', width: 100 },
        { title: '保存条件', key: 'keepCondition', width: 160 },
        { title: '抽样地点', key: 'samplingPlace', width: 160 },
        { title: '抽样地点（其他）', key: 'samplingPlaceRemark', width: 200 },
        { title: '抽样日期', key: 'samplingDate', width: 200, date: true },
        { title: '日期类型', key: 'dateType', width: 160 },
        { title: '日期', key: 'dateTime', width: 120, date: true },
        { title: '样品形态', key: 'shape', width: 100 },
        { title: '接收日期', key: 'receiveDate', width: 120, date: true },
        { title: '备注', key: 'remark' }
      ],
      iconMsg: [
        {
          type: 'ios-clock',
          id: '',
          name: '操作日志',
          componentName: 'SampleRecord'
        },
        { type: 'md-cloud', id: '', name: '附件', componentName: 'FileManage' }
      ],
      type: '',
      contractId: '', // 合同id
      selectData: [],
      currentComponent: '',
      formObj: {
        samplingNum: '',
        name: '',
        num: '',
        receiveStartDate: '',
        receiveEndDate: '',
        detectType: ''
      },
      dateList: [],
      searchOpen: false
    }
  },
  computed: {
    tableHeight: function() {
      return this.$tableHeight('tableModal')
    }
  },
  methods: {
    // 接收日期
    _receiveChange(data) {
      this.formObj.receiveStartDate = data[0]
      this.formObj.receiveEndDate = data[1]
    },
    // 组件返回值
    _componentResult(data, msg) {
      switch (this.currentComponent) {
        case 'SelectPrinter':
          this._printerResult(data)
          break
        default:
          this._search()
      }
    },
    _detailModal(id) {
      // 查看
      if (this.type === 1) {
        // 政府
        this.currentComponent = 'FoodSampleGovernDetail'
        this.$store.dispatch('FoodSample/getByGovernId', id).then(() => {
          this.$nextTick(() => {
            this.$refs.refModal._open(this.$store.state.FoodSample.governModel)
          })
        })
      } else {
        this.currentComponent = 'FoodSampleCompanyDetail'
        this.$store.dispatch('FoodSample/getByCompanyId', id).then(() => {
          this.$nextTick(() => {
            this.$refs.refModal._open(this.$store.state.FoodSample.companyModel)
          })
        })
      }
    },
    _open(contractId, type) {
      this.formObj = this.$resetFields(this.formObj)
      this.dateList = []
      $('input[name=contractId]').val(contractId)
      this.contractId = contractId
      this.type = type
      this.selectIds = []
      this.$nextTick(() => {
        this._page()
      })
    },
    _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
      }
    },
    _formSearch() {
      this.$refs.pageTable._pageChange(1)
    },
    _iconClick(res, data, currentComponent) {
      this.currentComponent = currentComponent
      this.$nextTick(() => {
        switch (res) {
          case '操作日志':
            this.$refs.refModal._open(data.id)
            break
          case '附件':
            this.$refs.refModal._open(data.id, 'sampleId')
            break
        }
      })
    },
    _btnClick(msg, currentComponent) {
      this.currentComponent = currentComponent
      this.$nextTick(() => {
        switch (msg) {
          case '导出任务单':
            this._exportTaskForm()
            break
          case '导出检测任务单':
            this._exportTestTaskForm()
            break
          case '打印标签':
            this._selectPrinter('print-label')
            break
          case '自定义打印':
            if (this.selectData.length === 0) {
              this.$Message.warning('请至少选择一条样品信息')
            } else {
              this._cusTomePrint()
            }
            break
          case '出库':
            if (this.selectData.length === 0) {
              this.$Message.warning('请至少选择一条样品信息！')
            } else {
              this.$refs.refModal._open(this.selectIds, 'alreadyOutStorage')
            }
            break
          case '扫码出库':
            this.$refs.refModal._open('alreadyScanOutStorage')
            break
          case '追加检测项目':
            this._importItem()
            break
          case '复制历史样品检测项目':
            this._copyHisItem()
            break
          case '追加检测项目包':
            this._importItemPackage()
            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)
        })
    },
    _exportTestTaskForm() {
      this.formObj.contractId = this.contractId
      const objcity = {
        param: 'ids',
        ids: this.selectIds,
        url: '',
        queryObj: this.$serializeFormSearch(this.formObj),
        msgContent: '数据量如果超过两万条，请分批次导出'
      }
      this.$store
        .dispatch(
          'ReportExport/getById',
          'food-sample-manage-export-test-table'
        )
        .then(() => {
          const result = this.$store.state.ReportExport.model
          objcity.url = result
          this.$exportByQuery(objcity)
        })
    },
    _search() {
      this._page()
    },
    _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
      }
    },
    // 追加检测项目包
    _importItemPackage() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this._judge('package')
      }
    },
    // 追加检测项目
    _importItem() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this._judge('item')
      }
    },
    // 复制历史项目
    _copyHisItem() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this._judge('copyHisItem')
      }
    },
    _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 {
        // eslint-disable-next-line no-undef
        http.open(
          '/food/report/excel/sheet?_u=db样品来源.report.xml&ids=' + ids
        )
      }
    },

    _judge(msg) {
      this.$store
        .dispatch('FoodSample/getSampleStatus', {
          ids: this.selectIds.join(',')
        })
        .then(() => {
          const result = this.$store.state.FoodSample.list
          if (result) {
            // 选中的是同一个 状态的样品
            // FLOW_RECEIVE--待接收
            this.sampleStatus = result.status.value
            if (this.sampleStatus === 'FLOW_RECEIVE') {
              // 选择检测项目后--直接保存
              this.$refs.refModal._open(this.selectIds, this.selectData[0])
            } else {
              // 弹出询问框
              this.$refs.typeModal._open(
                msg,
                this.selectIds,
                this.selectData[0]
              )
            }
          }
        })
    },
    /** ********************************导出任务单 -start********************************************/
    _exportTaskForm() {
      const ids = this.selectIds
      if (ids.length === 0) {
        this.$Message.warning('请至少选择一条数据')
      } else {
        this.$store
          .dispatch(
            'ReportExport/getById',
            'food-sample-manage-export-task-form1'
          )
          .then(() => {
            const result = this.$store.state.ReportExport.model
            window.open(
              this.$judgeUrlChar(result) + 'ids=' + this.selectIds,
              '_blank'
            )
          })
      }
    },
    /** ********************************导出任务单 -end********************************************/
    // 选择完打印机之后
    _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)
      }
    }
  }
}
</script>
