<template>
  <div>
    <!--内容-->
    <div class="layout-content-padding">
      <div class="layout-content-main">
        <Row>
          <!--查询-->
          <Col span="24">
            <Form id="search-form" :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.entrustCode" name="entrustCode" placeholder="请输入样品编号" clearable/>
              </Form-item>
              <Form-item class="search-item" label="试样编号:">
                <Input @on-enter="_formSearch" v-model="formObj.sampleCode" name="sampleCode" placeholder="请输入样品名称" clearable/>
              </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">
          <div style="display: flex;padding-bottom: 10px;">
            <div v-for="(item,index) in contList" :key="index" class="reimbursement-item">
              <p :class="item.color?item.color:''">{{item.value}}</p>
              <p>{{item.name}}</p>
            </div>
          </div>
          </Col>
          <!-- 表格 -->
          <Col span="24">
            <PTVXETable
              id="samplePreManage"
              ref="pageTable"
              :tableHeight="tableHeight"
              :getPage="getPage"
              @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"
                :min-width="200"
                :fixed="item.fixed?item.fixed:undefined"
                sortable
              >
                <template slot-scope="scope">
                  <div v-if="item.key==='status'">
                    {{scope.row[item.key]===undefined?'':scope.row[item.key].display}}
                  </div>
                  <a v-else-if="item.key==='code'" @click.stop="_detailModal(scope.row)">{{scope.row[item.key]}}</a>
                  <a v-else-if="item.key==='sampleSn'"
                     @click.stop="_sampleDetailModal(scope.row)">{{scope.row[item.key]}}</a>
                  <div v-else-if="item.key==='backupPlace'" @click.stop="_handleIndex(scope)">
                    <div v-if="editIndex!==scope.rowIndex">{{scope.row[item.key]}}</div>
                    <div v-else>
                      <AutoCompletes :value="scope.row.backupPlace" :downData="locList" @on-result-change="_locChange"
                                     name="backupPlace" placeholder="请输入或选择存储位置" focus
                                     show-key="backupPlace"></AutoCompletes>
                    </div>
                  </div>
                  <div v-else-if="item.key==='storageCondition'" @click.stop="_handleIndex(scope)">
                    <div v-if="editIndex!==scope.rowIndex">{{scope.row[item.key]}}</div>
                    <div v-else>
                      <el-select v-model="scope.row.storageCondition" clearable style="width:100%" size="small">
                        <el-option v-for="item in conditionList" :value="item.name" :key="item.name">{{ item.name }}
                        </el-option>
                      </el-select>
                    </div>
                  </div>
                  <div v-else-if="item.key==='handleQuantity'" @click.stop="_handleIndex(scope)">
                    <div v-if="editIndex!==scope.rowIndex">
                      {{scope.row[item.key]}}{{scope.row['sampleUnit'] &&
                      scope.row['handleQuantity']?scope.row['sampleUnit']:''}}
                    </div>
                    <div v-else>
                      <Row>
                        <Col span="18">
                          <el-input v-model="scope.row.handleQuantity" placeholder="处理数量" clearable size="small"/>
                        </Col>
                        <Col span="6">
                          <div style="line-height: 32px">{{scope.row['sampleUnit']?scope.row['sampleUnit']:''}}</div>
                        </Col>
                      </Row>
                    </div>
                  </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>
              <template slot="col">
                <vxe-table-column
                  :width="80"
                  title="操作"
                  align="center"
                  fixed="right">
                  <template slot-scope="scope">
                    <VXEIconList :msg="editIndex===scope.rowIndex?iconMsgSave:iconMsg" @on-result-change="_iconClick"
                                 :rowData="scope.row" :rowIndex="scope.rowIndex"></VXEIconList>
                  </template>
                </vxe-table-column>
              </template>
            </PTVXETable>
          </Col>
        </Row>
      </div>
    </div>
  </div>
</template>
<script>
import AutoCompletes from '../../../../components/base/AutoCompletes'
// eslint-disable-next-line no-unused-vars
import http from '../../../../api/http'
import { soilEntrust } from '../../../../api'
export default {
  components: {
    AutoCompletes
  },
  data() {
    return {
      currentComponent: '',
      searchOpen: false,
      formObj: {},
      selectData: [],
      selectIds: [],
      selectSampleIds: [],
      getPage: {},
      btn: [
        {
          type: 'primary',
          id: 'food-sample-preparation-his-all',
          name: '制备'
        },
        {
          type: 'primary',
          id: 'food-sample-preparation-his-no-pre',
          name: '无需制备'
        },
        {
          type: 'primary',
          id: 'food-sample-preparation-his-scan-pre',
          name: '扫码制备'
        },
        // { type: '', id: '', name: '填写存放信息' },
        // { type: '', id: '', name: '申请处理' },
        // { type: '', id: '', name: '导出' },
        {
          type: '',
          id: 'food-sample-prepare-record-export',
          name: '导出备样记录'
        }
      ],
      iconMsg: [
        { type: 'md-create', id: '', name: '编辑' } // food-sample-prepare-edit
      ],
      iconMsgSave: [{ type: 'ios-checkmark', id: '', name: '保存' }],
      pageColumns: [
        { title: '委托商', key: 'client', width: 180 },
        { title: '委托编号', key: 'entrustCode', width: 180 },
        { title: '试样编号', key: 'sampleCode', width: 180 },
        { title: '试样深度', key: 'sampleDepth', width: 180 },
        { title: '样品包装类型', key: 'samplePack', width: 180 },
        { title: '现场编号', key: 'siteNo', width: 180 },
        { title: '存储条件', key: 'conditions', width: 180 },
        { title: '备样位置', key: 'backupLocation', width: 180 },
        { title: '备样数量', key: 'quantity', width: 180 },
        { title: '备样人', key: 'backupUser', width: 140 },
        { title: '钻孔位置', key: 'boreholeLocation', width: 110 },
        { title: '钻孔名称', key: 'boreholeName', width: 160 },
        { title: '水深（米）', key: 'waterDepth', width: 160 },
        { title: '状态', key: 'status', width: 160 }
        /*  {title: '处置方式', key: 'handleMethod', width: 120,}, */
      ],
      conditionList: [],
      locList: [],
      currentIndex: -1,
      editIndex: -1,
      endDateBegin: '',
      endDateEnd: '',
      contList: [
        { key: 'backupCount', name: '今日新增数量', value: 0 },
        {
          key: 'backupCountOver',
          name: '超期数量',
          value: 0,
          color: 'red-color'
        },
        {
          key: 'backupCountWarn',
          name: '预警数量',
          value: 0,
          color: 'warning-color'
        }
      ],
      // 只看预警和超期样品
      warnAndOver: 0,
      sampleHandleValue: '',
      issueDateBegin: '',
      issueDateEnd: '',
      isEligible: ''
    }
  },
  computed: {
    tableHeight: function() {
      if (this.searchOpen) {
        return this.$tableHeight('', 385)
      } else {
        return this.$tableHeight('', 300)
      }
    },
    colorComputed() {
      return function(date) {
        if (this.$warningValue(date) < 0) {
          return '#eb6877' // 红色
        } else if (
          this.$warningValue(date) >= 0 &&
          this.$warningValue(date) <= this.sampleHandleValue
        ) {
          return '#f90' // 橙色
        }
      }
    }
  },
  mounted() {
    // 样品存储期限预警
    // this.sampleHandleValue = Number(localStorage.getItem('sampleHandleValue'))
    // this._getLocList()
    // this._getConditionList()
    // this._getBackUpCount()
  },
  methods: {
    // 签发日期
    _issueDateChange(date) {
      this.issueDateBegin = date[0]
      this.issueDateEnd = date[1]
    },
    // 重新请求page以及备样数量
    _relPage() {
      this._page()
      // this._getBackUpCount()
    },
    // 查询卡片备样数量
    _getBackUpCount() {
      this.$store.dispatch('FoodSampleBackup/backUpCount').then(() => {
        const result = this.$store.state.FoodSampleBackup.model
        const length = this.contList.length
        for (let i = 0; i < length; i++) {
          this.$set(this.contList[i], 'value', result[this.contList[i].key])
        }
      })
    },
    // 选择时间
    _endDateChange(data) {
      this.getPage.records[this.currentIndex].endDate = data
    },
    // 查询-接收日期
    _dateChange(data) {
      this.endDateBegin = data[0]
      this.endDateEnd = data[1]
    },
    _save() {
      this.$nextTick(function() {
        const data = {
          ids: this.getPage.records[this.currentIndex].id,
          backupPlace: this.getPage.records[this.currentIndex].backupPlace,
          storageCondition: this.getPage.records[this.currentIndex]
            .storageCondition,
          endDate: this.getPage.records[this.currentIndex].endDate,
          handleQuantity: this.getPage.records[this.currentIndex].handleQuantity
        }
        this.$store.dispatch('FoodSampleBackup/batchEdit', data).then(() => {
          if (this.$store.state.FoodSampleBackup.success) {
          } else {
            this.$msgTip('error', '保存失败！')
          }
          this._relPage()
        })
      })
    },
    _iconClick(res, data, componentName, index) {
      this.currentIndex = index
      switch (res) {
        case '编辑':
          this.editIndex = index
          break
        case '保存':
          console.log('保存')
          // if (data.endDate !== '') {
          //   // 非空情况下格式化赋值，如果不判断会格式化为当天的日期
          //   this._endDateChange(this.$dateformat(data.endDate, 'yyyy-mm-dd'))
          // }
          // this._save()
          this.editIndex = -1
          break
      }
    },
    _locChange(msg, data) {
      switch (msg) {
        case 'select':
          this.getPage.records[this.currentIndex].backupPlace = data.backupPlace
          break
        case 'query':
          this.getPage.records[this.currentIndex].backupPlace = data.backupPlace
          this._getLocList(data.backupPlace)
          break
        case 'focus':
          this._getLocList()
          break
      }
    },
    _getLocList(data) {
      const obj = {}
      if (data) {
        obj.backupPlace = data
      }
      this.$store.dispatch('FoodSampleBackup/getPositionList', obj).then(() => {
        this.locList = this.$store.state.FoodSampleBackup.list
      })
    },
    _getConditionList() {
      this.$store.dispatch('LmsBaseDict/getItem', '保存方式').then(() => {
        this.conditionList = this.$store.state.LmsBaseDict.item
      })
    },

    _exportReceiveRecord() {
      // 导出备样记录
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条数据！')
      } else {
        const obj = {
          param: 'ids',
          ids: this.selectIds,
          url: ''
        }
        this.$store
          .dispatch('ReportExport/getById', 'food-sample-prepare-record-export')
          .then(() => {
            const result = this.$store.state.ReportExport.model
            obj.url = result
            this.$exportByQuery(obj)
          })
      }
    },

    // 操作的序号
    _handleIndex(data) {
      this.currentIndex = data.rowIndex
    },
    _btnClick(msg) {
      switch (msg) {
        case '制备':
          this._preMethod()
          break
        case '无需制备':
          this._noPreMethod()
          break
        case '扫码制备':
          this._scanPreMethod()
          break
        case '填写存放信息':
          this._batchEdit()
          break
        case '申请处理':
          this._handle()
          break
        case '导出':
          if (this.getPage.records.length === 0) {
            this.$Message.warning('暂无数据，不可导出')
          } else {
            this._export()
          }
          break
        case '导出备样记录':
          this._exportReceiveRecord()
          break
        case 'search':
          this.searchOpen = !this.searchOpen
          break
      }
    },
    // 制备
    _preMethod() {
      if (this.selectSampleIds.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        this.$refs.preModal._open(this.selectSampleIds)
      }
    },
    // 无需制备
    _noPreMethod() {
      if (this.selectSampleIds.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        this.$refs.noPreModal._open(this.selectSampleIds)
      }
    },
    _scanPreMethod() {
      this.$refs.scanPreModal._open()
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'page':
          this.getPage.records = []
          this.getPage = {
            total: this.$store.state.LmsFoodSamplePrepare.page.total,
            pages: this.$store.state.LmsFoodSamplePrepare.page.pages,
            current: this.$store.state.LmsFoodSamplePrepare.page.current,
            size: this.$store.state.LmsFoodSamplePrepare.page.size,
            records: []
          }
          const tableList = this.$store.state.LmsFoodSamplePrepare.page.records
          for (let i = 0; i < tableList.length; i++) {
            this.getPage.records.push({
              sampleId:
                tableList[i].sampleId !== undefined
                  ? tableList[i].sampleId
                  : '',
              sampleSn:
                tableList[i].sampleSn !== undefined
                  ? tableList[i].sampleSn
                  : '',
              sampleName:
                tableList[i].sampleName !== undefined
                  ? tableList[i].sampleName
                  : '',
              backupPlace:
                tableList[i].backupPlace !== undefined
                  ? tableList[i].backupPlace
                  : '',
              cname: tableList[i].cname !== undefined ? tableList[i].cname : '',
              storageCondition:
                tableList[i].storageCondition !== undefined
                  ? tableList[i].storageCondition
                  : '',
              quantity:
                tableList[i].quantity !== undefined
                  ? tableList[i].quantity
                  : '',
              sampleQuantity:
                tableList[i].sampleQuantity !== undefined
                  ? tableList[i].sampleQuantity
                  : '',
              handleQuantity:
                tableList[i].handleQuantity !== undefined
                  ? tableList[i].handleQuantity
                  : '',
              sampleUnit:
                tableList[i].sampleUnit !== undefined
                  ? tableList[i].sampleUnit
                  : '',
              endDate:
                tableList[i].endDate !== undefined
                  ? new Date(tableList[i].endDate)
                  : '',
              handleMethod:
                tableList[i].handleMethod !== undefined
                  ? tableList[i].handleMethod
                  : '',
              id: tableList[i].id !== undefined ? tableList[i].id : '',
              contractName:
                tableList[i].contractName !== undefined
                  ? tableList[i].contractName
                  : '',
              code: tableList[i].code !== undefined ? tableList[i].code : '',
              contractSn:
                tableList[i].contractSn !== undefined
                  ? tableList[i].contractSn
                  : '',
              progress:
                tableList[i].progress !== undefined
                  ? tableList[i].progress
                  : '',
              type: tableList[i].type !== undefined ? tableList[i].type : '',
              issueDate:
                tableList[i].issueDate !== undefined
                  ? tableList[i].issueDate
                  : '',
              sampleRemark:
                tableList[i].sampleRemark !== undefined
                  ? tableList[i].sampleRemark
                  : '',
              contractRemark:
                tableList[i].contractRemark !== undefined
                  ? tableList[i].contractRemark
                  : '',
              isEligible:
                tableList[i].isEligible !== undefined
                  ? tableList[i].isEligible
                  : '',
              remark:
                tableList[i].remark !== undefined ? tableList[i].remark : '',
              contractId:
                tableList[i].contractId !== undefined
                  ? tableList[i].contractId
                  : ''
            })
          }
          this.selectIds = []
          this.selectData = []
          this.selectSampleIds = []
          break
        case 'selectData':
          this.selectData = data
          this.selectIds = []
          this.selectSampleIds = []
          for (let i = 0; i < data.length; i++) {
            this.selectIds.push(data[i].id)
            this.selectSampleIds.push(data[i].sampleId)
          }
          break
        case 'changeSize':
          this._page()
          break
      }
    },
    _formSearch() {
      this.$refs.pageTable._pageChange(1)
      // this._getBackUpCount()
    },
    _page: async function() {
      this.editIndex = -1
      Object.assign(this.formObj, this.$refs.pageTable._searchParams())
      console.log('this.formObj', this.formObj)
      const result = await soilEntrust.pageBackup(
        this.$serializeForm(this.formObj)
      )
      if (result) {
        this.$refs.pageTable._hideLoading()
        this.getPage = result
      }
    },
    _batchEdit() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请选择一条或多条数据！')
      } else {
        this.$refs.editModal._open(this.selectData)
      }
    },
    _handle() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请选择一条或多条数据！')
      } else {
        this.$refs.applyModal._open(this.selectData)
      }
    },
    // 委托详情
    _detailModal(data) {
      // 查看
      this.$store.dispatch('FoodContract/getById', data.contractId).then(() => {
        if (data.type === 0) {
          // 企业委托 ’0‘
          this.currentComponent = 'FoodContractCompanyDetail'
        } else {
          // 政府委托 ’1‘
          this.currentComponent = 'FoodContractGovernDetail'
        }
        this.$nextTick(() => {
          this.$refs.refModal._open(this.$store.state.FoodContract.model)
        })
      })
    },
    // 样品详情
    _sampleDetailModal(data) {
      if (data.type === 1) {
        // 政府
        this.currentComponent = 'FoodSampleGovernDetail'
        this.$nextTick(() => {
          this.$store
            .dispatch('FoodSample/getByGovernId', data.sampleId)
            .then(() => {
              this.$refs.refModal._open(
                this.$store.state.FoodSample.governModel
              )
            })
        })
      } else {
        this.currentComponent = 'FoodSampleCompanyDetail'
        this.$nextTick(() => {
          this.$store
            .dispatch('FoodSample/getByCompanyId', data.sampleId)
            .then(() => {
              this.$refs.refModal._open(
                this.$store.state.FoodSample.companyModel
              )
            })
        })
      }
    },
    /** *********************************导出-begin*********************************************/
    _export() {
      let result = []
      if (this.selectData.length === 0) {
        // 导出全部数据
        this.$store
          .dispatch('LmsFoodSamplePrepare/page', this._searchParams())
          .then(() => {
            result = this.$store.state.LmsFoodSamplePrepare.page.records
            this.$Modal.confirm({
              title: '提示',
              content:
                this.selectData.length === 0
                  ? '确定导出全部数据（最多导出5000条）？'
                  : '确定导出这' + result.length + ' 条数据？',
              onOk: () => {
                this.$exportExcel(
                  'samplePreManage',
                  '备样记录',
                  this.pageColumns,
                  result
                )
              }
            })
          })
      } else {
        // 只导出选中的数据
        result = this.selectData
        this.$Modal.confirm({
          title: '提示',
          content:
            this.selectData.length === 0
              ? '确定导出全部数据（最多导出5000条）？'
              : '确定导出这' + result.length + ' 条数据？',
          onOk: () => {
            this.$exportExcel(
              'samplePreManage',
              '备样记录',
              this.pageColumns,
              result
            )
          }
        })
      }
    },
    // 参数
    _searchParams() {
      const data = this.$serialize('search-form')
      return this.$extend(data, { page: 1, rows: 5000 })
    }
    /** *********************************导出样品台账-end*********************************************/
  }
}
</script>
<style scoped>
/******副样、备样卡片********/
.reimbursement-item {
  flex: 1;
  border-radius: 5px;
  border: 1px solid #e8e8e8;
  padding-bottom: 10px;
}

.reimbursement-item + .reimbursement-item {
  margin-left: 20px;
}

.reimbursement-item p {
  text-align: center;
  margin: 0;
}

.reimbursement-item > p:first-child {
  font-size: 22px;
  line-height: 40px;
}
</style>
