<template>
  <div>
    <!--内容-->
    <div class="layout-content-padding">
      <div class="layout-content-main">
        <Row>
          <!--查询-->
          <Col span="24">
            <Form id="search-form-make-sample" :label-width="90" 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" 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" :showSearchBtn="true" @on-result-change="_btnClick"
                     class="contHide">
              <!--切换待认领任务-->
            </btn-list>
          </Col>
          <!-- 表格 -->
          <Col span="24">
            <PTVXETable ref="pageTable" :tableHeight="tableHeight" @on-result-change="_tableResultChange"
                            :getPage="getPage"  select-data>
              <vxe-table-column
                :field="item.key"
                :title="item.title"
                :min-width="item.width?item.width:200"
                :fixed="item.fixed?item.fixed:undefined"
                v-for="item in pageColumns"
                :key="item.key" sortable>
                <template slot-scope="scope">
                  <div v-if="item.display">{{scope.row[item.key]? scope.row[item.key].display: ''}}</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.judge">{{Number(scope.row[item.key])===1?'是':'否'}}
                  </div>
                  <div v-else-if="item.reported">
                    <div v-if="scope.row[item.key]>0" class="green-color">是</div>
                    <div v-else>否</div>
                  </div>
                  <div v-else-if="item.key === 'infoMaintain'">
                    <label v-if="scope.row.infoMaintain === 'no'" class="green-color">信息已维护</label>
                    <label v-else-if="scope.row.infoMaintain === 'yes'" class="red-color">信息待维护</label>
                    <label v-else-if="scope.row.infoMaintain === 'none'">无</label>
                  </div>
                  <div v-else>{{scope.row[item.key]}}</div>
                </template>
              </vxe-table-column>
              <vxe-table-column
                :width="140"
                title="操作"
                align="center"
                fixed="right">
                <template slot-scope="scope">
                  <VXEIconList :msg="type === 0?iconMsg1:iconMsg" @on-result-change="_iconClick" :rowData="scope.row"
                               :rowIndex="scope.rowIndex"></VXEIconList>
                </template>
              </vxe-table-column>
            </PTVXETable>
          </Col>
        </Row>
      </div>
    </div>
    <SoilSampleItemManage ref="sampleItemManage" @on-result-change="_page"></SoilSampleItemManage>
  </div>
</template>
<script>
import { soilEntrust } from '../../../../api'
import SoilSampleItemManage from '../../../meter-entrust/SoilSampleItemManage'
/**
 * 按委托编制----管理样品
 */
export default {
  components: { SoilSampleItemManage },
  data() {
    return {
      currentComponent: '',
      searchOpen: false,
      btn: [
        {
          type: 'primary',
          id: 'food-report-make-push-to-gc',
          name: '推送至国抽平台'
        },
        { type: 'success', id: 'ZBC', name: '生成' },
        {
          type: 'success',
          id: 'food-report-make-select-template-create',
          name: '选择模板生成',
          componentName: 'CreateReport'
        },
        {
          type: 'primary',
          id: 'food-report-make-create-samples',
          name: '多样品生成',
          componentName: 'CreateReportBySamples'
        },
        {
          type: 'primary',
          id: 'food-report-make-edit-items',
          name: '批量维护检测项目',
          componentName: 'FoodItemBatchEditModal'
        },
        {
          type: '',
          id: 'food-report-make-sample-maintain-info',
          name: '信息维护',
          componentName: 'MaintainInfoModal'
        }
      ],
      getPage: {},
      detectionDate: '',
      pageColumns: [
        { title: '试样编号', key: 'sampleCode', width: 160, fixed: 'left' },
        { title: '试样深度', key: 'sampleDepth', width: 160 },
        { title: '土质描述', key: 'sampleDescribe', width: 160 },
        { title: '样品包装类型', key: 'samplePack', width: 160 },
        { title: '现场编号', key: 'siteNo', width: 130 },
        { title: '试验项目', key: 'experimentNames', width: 330 }
      ],
      selectIds: [],
      selectData: [],
      formObj: {
        entrustId: undefined,
        contractId: undefined,
        sampleCode: undefined
      },
      dateList: [],
      type: '',
      iconMsg: [
        {
          type: 'ios-beaker',
          id: '',
          name: '管理检测项目'
        },
        { type: 'md-trash', id: '', name: '删除' }
      ],
      iconMsg1: [
        {
          type: 'cloud',
          id: '',
          name: '样品附件',
          componentName: 'FileManage'
        },
        { type: 'compose', id: '', name: '编辑' }, // food-report-make-sample-edit
        {
          type: 'ios-upload',
          id: '',
          name: '上传',
          componentName: 'UploadReport'
        },
        {
          type: 'document-text',
          id: '',
          name: '项目台账',
          componentName: 'FoodItemEditModal'
        },
        {
          type: 'ios-clock',
          id: '',
          name: '操作记录',
          componentName: 'FoodSampleRecord'
        }
      ],
      dataPushedList: [{ value: 0, name: '否' }, { value: 1, name: '是' }],
      postUrl: 'FoodSample/pageSampleReportMake',
      currentId: ''
    }
  },
  computed: {
    tableHeight: function() {
      if (this.searchOpen) {
        return this.$tableHeight('tabSearch')
      } else {
        return this.$tableHeight('tabNoSearch')
      }
    }
  },
  mounted() {},
  methods: {
    // 初始化值
    // 当前列表有值，则不会重新调page接口
    _reportDateChange(data) {
      this.formObj.reportDateBegin = data[0]
      this.formObj.reportDateEnd = data[1]
    },
    _modalResult(data, msg) {
      switch (this.currentComponent) {
        case 'CreateReport':
          this.$emit('on-result-change', 'changeTab')
          break
        case 'ProgressByReport':
          // 进度条
          this.$emit('on-result-change', 'changeTab')
          break
        case 'FoodSampleCompanyEdit':
        case 'FoodSampleGovernLYEdit':
        case 'FoodSampleGovernEdit':
        case 'UploadReport':
          // 单个编辑
          this._updateRows()
          break
        default:
          this._page()
      }
    },
    // 更新ids数据
    _updateRows() {
      const obj = {
        url: this.postUrl,
        params: this.$serializeFormSearch(this.formObj)
      }
      obj.params.ids = this.currentId
      this.$refs.pageTable._updateRows(obj)
    },
    _iconClick(res, data, componentName) {
      this.currentComponent = componentName
      this.$nextTick(function() {
        switch (res) {
          case '管理检测项目':
            this._itemManage(data.id)
            break
          case '上传':
            this.currentId = data.id
            this.$refs.refModal._open(data.id)
            break
          case '项目台账':
            this.$refs.refModal._open(data)
            break
          case '操作记录':
            this._record(data.id)
            break
          case '编辑':
            this.currentId = data.id
            this._edit(data)
            break
          case '样品附件':
            this._upload(data.id)
            break
        }
      })
    },
    _itemManage(data) {
      // 管理检测项目
      this.$refs.sampleItemManage._open(data)
    },
    _upload(id) {
      // 上传文件
      this.$refs.refModal._open(id, 'sampleId')
    },
    _edit(data) {
      if (data.type === 0) {
        this.currentComponent = 'FoodSampleCompanyEdit'
        this.$store.dispatch('FoodSample/getByCompanyId', data.id).then(() => {
          this.$nextTick(function() {
            this.$refs.refModal._open(
              this.$store.state.FoodSample.companyModel,
              this.formObj.contractId
            )
          })
        })
      } else if (data.type === 2) {
        this.currentComponent = 'FoodSampleGovernLYEdit'
        this.$store.dispatch('FoodSample/getByGovernId', data.id).then(() => {
          this.$nextTick(function() {
            this.$refs.refModal._open(
              this.$store.state.FoodSample.governModel,
              this.formObj.contractId
            )
          })
        })
      } else {
        this.currentComponent = 'FoodSampleGovernEdit'
        this.$store.dispatch('FoodSample/getByGovernId', data.id).then(() => {
          this.$nextTick(function() {
            this.$refs.refModal._open(
              this.$store.state.FoodSample.governModel,
              this.formObj.contractId
            )
          })
        })
      }
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'page':
          this.selectIds = []
          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
      }
    },
    _open(entrustId) {
      // 初始化数据
      // this._resetData(contractId, type, personal)
      this.formObj.entrustId = entrustId
      this._page()
    },
    _page: async function() {
      Object.assign(this.formObj, this.$refs.pageTable._searchParams())
      const result = await soilEntrust.samplePage(
        this.$serializeForm(this.formObj)
      )
      if (result) {
        this.$refs.pageTable._hideLoading()
        this.getPage = result
      }
    },
    _formSearch() {
      this.$refs.pageTable._pageChange(1)
    },
    _record(id) {
      // 操作记录
      this.$refs.refModal._open(id)
    },
    _btnClick(msg, componentName) {
      this.currentComponent = componentName
      this.$nextTick(function() {
        switch (msg) {
          case '生成':
            this._createReport()
            break
          case '选择模板生成':
            this._judgeReport('create')
            break
          case '推送至国抽平台':
            this._pushToGC()
            break
          case '多样品生成':
            this._judgeReport('create-samples')
            break
          case '批量维护检测项目':
            if (this.selectIds.length === 0) {
              this.$Message.warning('请至少选择一条数据')
            } else {
              this.$refs.refModal._open(this.selectIds)
            }
            break
          case '信息维护':
            this._maintainInfo()
            break
          case 'search':
            this.searchOpen = !this.searchOpen
            break
        }
      })
    },
    // 信息维护
    _maintainInfo() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        this.$refs.refModal._open(this.selectIds, 2)
      }
    },
    // 推送至国抽平台
    _pushToGC() {
      const ids = this.selectIds
      if (ids.length === 0) {
        this.$Message.warning('请至少选择一条数据')
      } else {
        this.$Modal.confirm({
          title: '提示',
          content: '确定要推送这' + ids.length + '条数据至国抽平台？',
          loading: true,
          onOk: () => {
            this.$store
              .dispatch('FoodSample/pushDataToGC', { ids: ids.join(',') })
              .then(() => {
                this._resultChange('信息推送成功')
              })
          }
        })
      }
    },
    _resultChange(msg) {
      if (this.$store.state.FoodSample.success) {
        this.$Message.success(msg)
        this._page()
        this.selectIds = []
      }
      this.$Modal.remove()
    },
    // 生成报告
    _judgeReport(name) {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        switch (name) {
          case 'create':
            this.$refs.refModal._open(this.selectData)
            break
          case 'create-samples':
            this.$refs.refModal._open(this.selectIds)
            break
        }
      }
    },
    _createReport() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        const validateObj = { sampleIds: this.selectIds }
        // 先进行验证
        this.$store
          .dispatch('FoodSampleReport/generateAutomaticValidate', validateObj)
          .then(() => {
            if (this.$store.state.FoodSampleReport.success) {
              // 验证成功之后再建立连接，然后进行生成报告操作
              // 建立websocket连接
              const currentTime = new Date().getTime()
              // true --- 建立连接
              this.currentComponent = 'ProgressByReport'
              this.$nextTick(() => {
                this.$refs.refModal._open(this.selectIds.length, currentTime)
              })
              validateObj.seriesNo = currentTime
              this.$store
                .dispatch('FoodSampleReport/generateAutomatic', validateObj)
                .then(() => {})
            } else {
              // false --- 弹出选择模板框
              this.currentComponent = 'CreateReport'
              this.$nextTick(() => {
                this.$refs.refModal._open(this.selectData)
              })
            }
          })
      }
    }
  }
}
</script>
