<template>
  <div>
    <div>
      <!--内容-->
      <Row>
        <!--查询-->
        <Col span="24" style="padding-bottom: 5px">
          <Form id="search-wait" v-show="searchOpen" :label-width="100" inline onsubmit="return false">
            <label class="label-sign"></label>
            <Form-item label="试样编号:" class="search-item">
              <Input v-model="formObj.sampleCode" @on-enter="_formSearch" 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" :key="index" :value="item.value">{{item.name}}</Option>
              </Select>
            </Form-item>
            <Form-item label="试验科室:" class="search-item">
                <el-select v-model="formObj.groupId" @change="_selGroup" placeholder="请选择" clearable style="width: 100%">
                  <el-option
                    v-for="(item,index) in groupoptions"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
            </Form-item>
            <Form-item :label-width="150" label="试验项目/试验项目简写:" class="search-item">
              <Input v-model="formObj.experimentNames" @on-enter="_formSearch" style="width: 150px;" 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">
          <PTVXETableHeight
            ref="pageTable"
            :table-height="tableHeight"
            :get-page="getPage"
            :icon-msg="iconMsg"
            @on-result-change="_tableResultChange"
            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-if="item.key==='seniorType'">
                  <el-select v-model="scope.row.seniorType" @change="_selSeniorType(scope.row)" placeholder="请选择" clearable style="width: 100%">
                    <el-option
                      v-for="(data,index) in seniorTypeArray"
                      :key="index"
                      :label="data.name"
                      :value="data.name"
                    />
                  </el-select>
                </div>
                <div v-else>{{scope.row[item.key]}}</div>
              </template>
            </vxe-table-column>
          </PTVXETableHeight>
        </Col>
      </Row>
    </div>
    <!--选择领样人-->
    <storageSelect ref="locationModal" @on-result-change="_page()"></storageSelect>
    <SoilSampleItemManage ref="sampleItemManage" @on-result-change="_page"></SoilSampleItemManage>
    <KeepAdress ref="keepAdressModal" @on-result-change="_page"></KeepAdress>
    <SampleItemSelect ref="sampleItemSelectModal" @on-result-change="_itemImportBack" is-change />
    <SeniorSampleEdit ref="seniorSampleEditModal" @on-result-change="_page" is-change />
  </div>
</template>
<script>
import {
  soilAptitude,
  soilEntrust,
  soilSample,
  soilTest
} from '../../../../api'
import storageSelect from '../storageSelect'
import global from '../../../../api/config'
// import http from '../../../../api/http'
import SampleItemSelect from './SampleItemSelect'
import SoilSampleItemManage from './SoilSampleItemManage'
import SeniorSampleEdit from './SeniorSampleEdit'
import KeepAdress from './KeepAdress'
export default {
  components: {
    storageSelect,
    SoilSampleItemManage,
    SeniorSampleEdit,
    KeepAdress,
    SampleItemSelect
  },
  data() {
    return {
      btn: [
        { type: 'primary', id: 'alone-keep-callout', name: '调出' },
        { type: 'primary', id: 'alone-keep-edit', name: '编辑' },
        { type: 'primary', id: 'alone-keep-import', name: '导入试验项目' },
        {
          type: 'primary',
          id: 'alone-keep-export',
          name: '导出样品抽样单模板'
        }
      ],
      groupoptions: [],
      seniorTypeArray: [],
      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: 'receiveLocation', width: 130 },
        { title: '高级样品分类', key: 'seniorType', width: 130 },
        { title: '收样时间', key: 'receiveTime', width: 100, date: true },
        { title: '接收人', key: 'receiver', width: 100 },
        { title: '试验项目', key: 'experimentNames', width: 220 },
        { title: '试验项目简写', key: 'experimentShortNames', width: 220 },
        { title: '土质描述', key: 'sampleDescribe', width: 205 },
        { title: '样品包装类型', key: 'samplePack', width: 120 },
        { title: '备注', key: 'remark', width: 210 }
      ],
      iconMsg: [{ type: 'ios-list', id: 'alone-keep-item', name: '试验项目' }],
      type: '',
      contractId: '', // 合同id
      selectData: [],
      currentComponent: '',
      indexList: [],
      formObj: {
        samplingNum: '',
        name: '',
        num: '',
        detectType: '',
        standard: '',
        samplingLinkList: [],
        haveExp: undefined,
        groupName: undefined,
        groupId: undefined
      },
      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 'sampleMan':
          // 扫码接收并发放
          this.$refs.refModal._open('扫码接收发放', data)
          break
      }
    },
    _selectSampleLink(data) {
      console.log(data)
    },
    _selGroup(data) {
      console.log(data)
      this.formObj.groupId = data
    },
    async _selSeniorType(data) {
      console.log(data)
      const result = await soilTest.editSeniorType({
        id: data.id,
        seniorType: data.seniorType
      })
      if (result) {
        this.$Message.success('保存成功')
      }
    },
    // 组件返回值
    _componentResult(data, msg) {
      switch (this.currentComponent) {
        case 'SelectPrinter':
          this._printerResult(data)
          break
        case 'ReceiveScan':
          // 扫码接收
          this._searchTop()
          break
        default:
          this._search()
      }
    },
    _getGroupList: async function() {
      const result = await soilAptitude.getGroupList()
      if (result) {
        this.groupoptions = result
      }
    },
    _getSeniorTypeList: async function() {
      const result = await soilAptitude.getDictInfo({
        type: '高级样品分类',
        page: 1,
        rows: 50
      })
      if (result) {
        this.seniorTypeArray = result.records
      }
    },
    _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._getGroupList()
      this._getSeniorTypeList()
      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.pageAloneKeepSample(
        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.$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._exportTemplate()
            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._sampleReceive(this.selectIds)
            break
          case '样品留存':
            this._sampleKeep(this.selectIds)
            break
          case '调出':
            this._callOut()
            break
          case '导入试验项目':
            this._importItem()
            break
          case '编辑':
            this._editSeniorSample()
            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
        }
      })
    },
    _exportTemplate() {
      const data = {
        downloadUrl: '/soil/v1/excel/template_soil/SamplingList.xlsx'
        // downloadUrl: '/soil/v1/sample/export_sampling_list'
      }
      console.log(data)
      this.$Modal.confirm({
        title: '提示',
        content: '确定要导出该模板？',
        onOk: () => {
          this._download(data)
        }
      })
    },
    _download(data) {
      window.open(global.baseURL + data.downloadUrl, '_blank')
      // http.open(
      //   '/soil/v1/sample/export_sampling_list',
      //   { ids: this.selectIds.join(',') },
      //   '_blank'
      // )
    },
    _importItem() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请选择至少一条数据！')
      } else {
        this.$refs.sampleItemSelectModal._open()
      }
    },

    _editSeniorSample() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请选择至少一条数据！')
      } else {
        this.$refs.seniorSampleEditModal._open(this.selectIds)
      }
    },

    _itemImportBack(data) {
      console.log(data)
      if (data.length > 0) {
        const ids = []
        for (let i = 0; i < data.length; i++) {
          ids.push(data[i].id)
        }
        this._importItemOk(ids)
      }
    },
    _importItemOk: async function(ids) {
      const result = await soilSample.importExperiments({
        aptitudeIds: ids.join(','),
        ids: this.selectIds.join(',')
      })
      if (result) {
        this.$Message.success('导入成功')
        await this._page()
      }
    },
    _resultChange(msg) {
      this._page()
      this.$Message.success(msg)
      this.selectIds = []
    },
    _search() {
      this._page()
    },
    // 刷新上级页面
    _searchTop() {
      this._page()
      this.$emit('on-result-change')
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'page':
          this._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)
      }
    },
    _callOut(id) {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this.$Modal.confirm({
          title: '提示',
          content: '确定调出？',
          onOk: () => {
            this._callOutOk()
          }
        })
      }
    },
    _callOutOk: async function() {
      const result = await soilEntrust.callOutAloneKeepSample({
        ids: this.selectIds.join(',')
      })
      if (result) {
        this._resultChange('调出成功')
      }
    },
    // 样品接收
    _sampleReceive(id) {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        const ids = id.join(',')
        this.$refs.locationModal._open(ids)
      }
    },
    _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
      }
    }
  }
}
</script>
