<template>
  <div>
    <Row>
      <!--查询-->
      <Col span="24">
        <Form id="task-assign-sample-right" :label-width="70" inline onsubmit="return false">
          <label class="label-sign"></label>
          <Form-item class="search-item" label="委托编号:">
            <Input v-model="formObj.client" @on-enter="_formSearch" 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" @on-result-change="_btnClick" class="contHide"></btn-list>
      </Col>
      <!-- 表格 -->
      <Col span="24">
        <PTVXETable ref="pageTable" :pageColumns="pageColumns" :tableHeight="tableHeight"
                    @on-result-change="_tableResultChange" :icon-msg="iconMsg" :getPage="getPage" :table-name="tableName" :rows="100" is-task select-data>
          <vxe-table-column
            v-for="item in userColumns.length > 0 ?userColumns:pageColumns"
            :key="item.key"
            :field="item.key"
            :title="item.title"
            :min-width="item.width"
            :fixed="item.fixed?item.fixed:undefined"
            sortable>
            <template slot-scope="scope">
              <div v-if="item.key === 'name'" :style="{color:colorComputed(scope.row.planEndDate)}">
                {{scope.row[item.key]}}
              </div>
              <a v-else-if="item.key==='code'" @click.stop="_detailModal(scope.row)">{{scope.row[item.key]}}</a>
              <a v-else-if="item.key==='num'" @click.stop="_sampleDetail(scope.row)">{{scope.row[item.key]}}</a>
              <span v-else-if="item.key==='progress'">{{scope.row[item.key].display}}</span>
              <span
                v-else-if="item.date">{{scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd'):''}}</span>
              <span v-else-if="item.datetime">{{scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd HH:MM'):''}}</span>
              <span v-else>{{scope.row[item.key]}}</span>
            </template>
          </vxe-table-column>
          <VXESettingCol slot="setting" :pageColumns="pageColumns" :userColumns="userColumns"
                         @on-result-change="_resetColumn" :table-name="tableName"></VXESettingCol>
        </PTVXETable>
      </Col>
    </Row>
    <AssignPerson ref="personModal" @on-result-change="_assignBackData"></AssignPerson>
    <SelectOriTempRecord ref="recordModal" @on-result-change="_page"></SelectOriTempRecord>
    <SelEquip ref="selEquip" @on-result-change="_equipResult"></SelEquip>
    <IndexManage ref="indexModal" @on-result-change="_page"></IndexManage>
    <EquipManage ref="equipModal" @on-result-change="_page"></EquipManage>
  </div>
</template>
<script>
import Global from '../../../../api/config'
import { soilTest } from '../../../../api'
import AssignPerson from '../../../../components/user-info-single/assignPerson'
import SelectOriTempRecord from '../SelectOriTempRecord'
import SelEquip from '../../../../components/select-equip/SelEquip'
import IndexManage from '../IndexManage'
import EquipManage from '../EquipManage'
export default {
  components: {
    AssignPerson,
    SelectOriTempRecord,
    SelEquip,
    IndexManage,
    EquipManage
  },
  data() {
    return {
      // 定义表格名称----英文
      tableName: 'food-task-assign-item-right',
      formObj: {},
      // 用户自己选中的列
      userColumns: [],
      currentComponent: '',
      optionList: [
        { key: 'name', name: '检测项目', placeholder: '请输入检测项目' },
        { key: 'code', name: '委托编号', placeholder: '请输入委托编号' },
        { key: 'num', name: '样品编号', placeholder: '请输入样品编号' },
        { key: 'sampleName', name: '样品名称', placeholder: '请输入样品名称' },
        { key: 'testBasis', name: '检测依据', placeholder: '请输入检测依据' },
        {
          key: 'resultDate',
          name: '数据出具日期',
          placeholder: '请选择数据出具日期',
          date: true
        },
        {
          key: 'receiveDate',
          name: '接样日期',
          placeholder: '请选择接样日期',
          date: true
        },
        { key: 'tester', name: '主检人', placeholder: '请输入主检人' },
        { key: 'detectType', name: '样品类别', placeholder: '请输入样品类别' }
      ],
      btn: [
        { type: 'success', id: '', name: '填写原始记录' },
        { type: 'success', id: '', name: '完成提交' },
        { type: 'success', id: '', name: '设备' },
        { type: '', id: 'food-task-assign-adjust-group', name: '调整分组' },
        {
          type: '',
          id: 'food-task-assign-plan-date',
          name: '设置计划完成时间'
        },
        { type: '', id: 'food-task-assign-maintain-info', name: '信息维护' }
      ],
      iconMsg: [
        { type: 'ios-book', id: '', name: '查看原始记录' },
        { type: 'md-apps', id: '', name: '查看指标' },
        { type: 'ios-flask', id: '', name: '设备列表' }
      ],
      getPage: {},
      pageColumns: [
        { title: '试验项目', key: 'name', width: 120, fixed: 'left' },
        { title: '试样编号', key: 'sampleCode', width: 180 },
        { title: '试样深度', key: 'sampleDepth', width: 180 },
        { title: '试样包装类型', key: 'samplePack', width: 180 },
        { title: '是否填写原始记录', key: 'recorded', width: 180 },
        { title: '状态', key: 'progress', width: 180 },
        { title: '大类', key: 'mainType', width: 140 },
        { title: '小类', key: 'smallType', width: 140 },
        { title: '检测方法', key: 'testMethod', width: 260 },
        { title: '检测依据', key: 'testBasis', width: 140 },
        { title: '检测科室', key: 'groupName', width: 150 }
      ],
      leftSelectData: [],
      sampleIds: [],
      selectIds: [], // 检测项目id
      selectData: [], // 检测项目data
      selectSampleIds: [], // 样品ids
      result: [],
      sampleNames: '', // 没有计划完成时间的样品名
      defaultPlanDate: null, // 是否有字典
      warningValue: ''
    }
  },
  computed: {
    tableHeight: function() {
      return this.$tableHeight('tabSearch')
    },
    colorComputed() {
      return function(val) {
        return val - new Date().getTime() > this.warningValue * 86400000
          ? '#606266'
          : val - new Date().getTime() <= 0
            ? '#eb6877'
            : '#f90'
      }
    }
  },
  mounted() {
    // this._dicSearch()
  },
  methods: {
    // 获取column
    _getColumn() {
      this.$refs.pageTable._getColByTableName()
    },
    // 重置column
    _resetColumn(colList) {
      this.userColumns = colList
      this.$refs.pageTable._loadColumn(colList)
    },
    // 从字典查预警期
    _dicSearch() {
      const data = ['食品检测预警天数', '食品默认计划完成时间']
      this.$store.dispatch('LmsBaseDict/listDict', data).then(() => {
        const result = this.$store.state.LmsBaseDict.list
        // eslint-disable-next-line camelcase
        const result_1 = result[0]
        // eslint-disable-next-line camelcase
        const result_2 = result[1]
        //  1食品检测预警天数
        if (result_1.length !== 0) {
          this.warningValue = result_1[0].name
        }
        //  2食品默认计划完成时间
        this.defaultPlanDate =
          result_2.length !== 0
            ? result_2[0].name === '是'
              ? (this.defaultPlanDate = true)
              : (this.defaultPlanDate = false)
            : (this.defaultPlanDate = false)
      })
    },
    _selInputResult1(msg, data) {
      switch (msg) {
        case 'keyword':
          this.$refs.selInput2._setCompareKeyword(data)
          break
        case 'search':
          this._formSearch()
          break
      }
    },
    _selInputResult2(msg, data) {
      switch (msg) {
        case 'keyword':
          this.$refs.selInput1._setCompareKeyword(data)
          break
        case 'search':
          this._formSearch()
          break
      }
    },
    _modalResult(data) {
      switch (this.currentComponent) {
        case 'AssignPerson':
          if (this.defaultPlanDate) {
            this._trueDefault(data)
          } else {
            this._userResult(data)
          }
          break
        case 'EndDateModal':
          // if(this.defaultPlanDate){
          //   this._endDate()
          // } else {
          this._page()
          // }
          break
        case 'UserGroup':
          this._userGroupResult(data)
          break
        default:
          this._page()
      }
    },
    // 为 true时，有字典按人分配
    _trueDefault(data) {
      const tempData = {
        ids: this.selectIds.join(','),
        personId: data.userId,
        personName: data.realname,
        groupId: data.groupId,
        groupName: data.groupName
      }
      Object.assign(tempData, { planDate: null })
      this.$store.dispatch('FoodItem/personAllot', tempData).then(() => {
        if (this.$store.state.FoodItem.success) {
          this.sampleNames = ''
          this._page()
          this._resultChange('分配成功！')
        }
      })
    },
    // 设置时间
    _endDate() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        const user = Global.getUserInfo('userInfo')
        this.currentComponent = 'AssignPerson'
        this.$nextTick(function() {
          this.$refs.refModal._openGoupByUserId('分配人员', user.id, 'itemTree')
        })
      }
    },
    _equipResult: async function(res) {
      console.log(res)
      const tempData = {}
      tempData.equipList = []
      res.map((item, index) => {
        tempData.equipList.push({
          equipId: item.id,
          equipName: item.name,
          acquisitionCommand: item.acquisitionCommand,
          brand: item.brand,
          collectionAddress: item.acquisitionAddress,
          collectionType: item.acquisitionType,
          equipNum: item.labNum,
          ipAddress: item.ipAddress,
          labNum: item.classId,
          spec: item.spec
        })
      })
      tempData.expIds = this.selectIds
      const result = await soilTest.addExpEquip(tempData)
      if (result) {
        this.$Message.success('添加成功')
      }
    },
    // 调整分组
    _userGroupResult(data) {
      const tempData = {
        groupId: data.id,
        groupName: data.name,
        ids: this.selectIds.join(',')
      }
      this.$store.dispatch('FoodItem/adjustTestGroup', tempData).then(() => {
        this._resultChange('调整成功')
      })
    },
    _resultChange(msg) {
      this.$Message.success(msg)
      this._page()
      this.$emit('on-result-change')
      this.selectIds = []
    },
    async _btnClick(msg) {
      switch (msg) {
        case '试验项目分配':
          this._userAssign()
          break
        case '填写原始记录':
          this._addRecord()
          break
        case '完成提交':
          this._submitItem(this.selectData)
          break
        case '设备':
          this._selectEquipment()
          break
        case '按组分配':
          await this._reportDueDate()
          await this._groupAssign()
          break
        case '调整分组':
          if (this.selectIds.length === 0) {
            this.$Message.warning('请至少选择=一条数据')
          } else {
            this.currentComponent = 'UserGroup'
            this.$nextTick(() => {
              this.$refs.refModal._open()
            })
          }
          break
        case '设置计划完成时间':
          this.currentComponent = 'EndDateModal'
          this.$nextTick(function() {
            this._changeDate()
          })
          break
        case '信息维护':
          this._maintainInfo()
          break
      }
    },
    _selectEquipment() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        this.$refs.selEquip._open('sample-input')
      }
    },
    _submitItem(data) {
      console.log(data)
      this.$Modal.confirm({
        title: '提示',
        content: '确定提交该数据？',
        onOk: () => {
          this._submitOk()
        }
      })
    },
    _submitOk: async function() {
      const result = await soilTest.endExp(this.selectIds.join(','))
      if (result) {
        this._resultChange('提交成功')
      }
    },
    _addRecord() {
      if (this.selectIds.length === 0) {
        this.$message.warning('请至少选择一条数据')
      } else {
        const errorInfo = []
        for (let i = 0; i < this.selectData.length; i++) {
          console.log(this.selectData[i].recorded)
          if (this.selectData[i].recorded === '是') {
            errorInfo.push(this.selectData[i].index + 1)
          }
        }
        if (errorInfo.length !== 0) {
          this.$Message.warning('第' + errorInfo + '条数据已填写原始记录')
        } else {
          console.log('打开填写原始记录界面')
          this.$refs.recordModal._open(this.selectIds, this.entrustId)
        }
      }
    },
    // 信息维护
    _maintainInfo() {
      if (this.selectSampleIds.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        this.currentComponent = 'MaintainInfoModal'
        this.$nextTick(() => {
          this.$refs.refModal._open(this.selectSampleIds, 2)
        })
      }
    },
    _changeDate() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        const tempData = {
          ids: this.selectIds.join(',')
        }
        this.$refs.refModal._open(tempData, 'planDate')
      }
    },
    _open(id, data) {
      this.getPage.records = []
      console.log(id)
      this.sampleIds = data
      if (data.length === 0) {
        this.$set(this.getPage, 'records', [])
        this.$set(this.getPage, 'total', 0)
        this.$set(this.getPage, 'current', 1)
        this.selectSampleIds = []
        this.selectIds = []
        this.selectData = []
        this.result = []
      } else {
        this._page()
      }
    },
    _refresh() {
      this.$emit('on-result-change')
    },
    _formSearch() {
      this.$refs.pageTable._pageChange(1)
    },
    _searchParams() {
      const obj = {}
      const obj1 = this.$refs.selInput1._getFormObj()
      const obj2 = this.$refs.selInput2._getFormObj()
      const obj3 = { foodItemList: this.leftSelectData }
      Object.assign(obj, obj1, obj2, obj3)
      return obj
    },
    _page: async function() {
      Object.assign(this.formObj, this.$refs.pageTable._searchParams())
      this.formObj.sampleIds = this.sampleIds
      const result = await soilTest.pageTest(this.$serializeForm(this.formObj))
      if (result) {
        this.$refs.pageTable._hideLoading()
        this.$refs.pageTable._checkAll()
        this.getPage = result
      }
    },
    _tableResultChange(msg, data) {
      const selectIds = []
      switch (msg) {
        case 'page':
          this._page()
          // this.result = this.getPage.records;
          // this.$nextTick(() => {
          // this.$refs.pageTable._checkAll()
          // })
          // if (this.getPage.records.length === 0) {
          //   this.$emit('on-result-change')
          // }
          break
        case 'selectData':
          for (let i = 0; i < data.length; i++) {
            selectIds.push(data[i].id)
          }
          this.selectIds = selectIds
          this.selectData = data
          break
        case 'iconClick':
          this._iconClick(data.name, data.rowData, data.componentName)
          break
        case 'table-col':
          // 用户选中的表格列
          this.userColumns = data
          break
        case 'changeSize':
          this._page()
          // this.$refs.pageTable._checkAll()
          break
      }
    },
    _iconClick(res, data, currentComponent) {
      this.$nextTick(() => {
        switch (res) {
          case '查看原始记录':
            console.log(data)
            if (data.recordId) {
              // this._viewRecord('1309434759937146882')
              this._viewRecord(data.recordId)
            } else {
              this.$Message.warning('未填写原始记录')
            }
            break
          case '查看指标':
            this._indexManage(data)
            break
          case '设备列表':
            this._equipManage(data)
            break
        }
      })
    },
    _indexManage(data) {
      this.$refs.indexModal._open(data)
    },
    _equipManage(data) {
      this.$refs.equipModal._open(data)
    },
    _viewRecord(recordId) {
      // layx.iframe('labRecordWriteOriView', '原始记录预览', Global.recordURL + '/print/v1/form/' + originalRecordId, {
      // eslint-disable-next-line no-undef
      layx.iframe(
        'labRecordWriteOriView',
        '原始记录预览',
        Global.recordURL + '/print/v1/form/' + recordId + '?type=ENVTESTMAKE',
        {
          event: {
            onload: {
              after: function(layxWindow, winform) {
                // eslint-disable-next-line no-undef
                layx.max(winform.id)
              }
            }
          }
        }
      )
    },
    // 按人分配  选人选时间
    _userAssign() {
      const user = Global.getUserInfo('userInfo')
      console.log(user)
      this.$refs.personModal._openGoup('分配人员', 'itemTree')
      // if (this.defaultPlanDate) {
      //   // 有字典
      //   if (this.sampleNames === '') {
      //     // 有计划完成时间
      //     const user = Global.getUserInfo('userInfo')
      //     this.currentComponent = 'AssignPerson'
      //     this.$nextTick(function() {
      //       this.$refs.refModal._openGoupByUserId(
      //         '分配人员',
      //         user.id,
      //         'itemTree'
      //       )
      //     })
      //   } else {
      //     // 有字典，无计划完成时间的
      //     this.$Modal.confirm({
      //       title: '提示',
      //       content:
      //         '所选项目中含有未设置计划完成时间的' +
      //         `${this._reportDueDate()}` +
      //         '请确认！',
      //       onOk: () => {}
      //     })
      //   }
      // } else {
      //   // 无字典
      //   this.currentComponent = 'EndDateModal'
      //   this.$nextTick(() => {
      //     this._endDate()
      //   })
      // }
    },
    // 遍历出计划时间为空的样品名
    _reportDueDate() {
      const sampleNames = []
      for (let i = 0; i < this.result.length; i++) {
        if (!this.result[i].planEndDate) {
          sampleNames.push(this.result[i].name)
        }
      }
      this.sampleNames = [...new Set(sampleNames)].join(',')
      return this.sampleNames
    },
    _userResult(data) {
      const tempData = {
        ids: this.selectIds.join(','),
        personId: data.userId,
        personName: data.realname,
        groupId: data.groupId,
        groupName: data.groupName
      }
      this.currentComponent = 'EndDateModal'
      this.$nextTick(function() {
        this.$refs.refModal._open(tempData, 'user')
      })
    },
    // 按组分配  选时间
    _groupAssign() {
      if (this.defaultPlanDate) {
        // 有字典
        if (this.sampleNames === '') {
          // 有计划完成时间
          const tempData = {
            ids: this.selectIds.join(',')
          }
          Object.assign(tempData, { planDate: null })
          this.$store.dispatch('FoodItem/groupAllot', tempData).then(() => {
            if (this.$store.state.FoodItem.success) {
              this.$Message.success('分配成功!')
              this._page()
            }
          })
        } else {
          // 有字典，无计划完成时间
          this.$Modal.confirm({
            title: '提示',
            content:
              '所选项目中含有未设置计划完成时间的' +
              `${this._reportDueDate()}` +
              '请确认！',
            onOk: () => {}
          })
        }
      } else {
        // 无字典的
        // eslint-disable-next-line no-lonely-if
        if (this.selectIds.length === 0) {
          this.$Message.warning('请至少选择一条数据！')
        } else {
          const tempData = {
            ids: this.selectIds.join(',')
          }
          this.currentComponent = 'EndDateModal'
          this.$nextTick(function() {
            this.$refs.refModal._open(tempData, 'group')
          })
        }
      }
    },
    // 委托详情
    _detailModal(data) {
      this.$store.dispatch('FoodContract/getById', data.contractId).then(() => {
        if (data.type === 1) {
          this.currentComponent = 'FoodContractGovernDetail'
        } else {
          this.currentComponent = 'FoodContractCompanyDetail'
        }
        this.$nextTick(function() {
          this.$refs.refModal._open(this.$store.state.FoodContract.model)
        })
      })
    },
    _assignBackData(data) {
      console.log(data)
      const tempData = {}
      tempData.ids = this.selectIds.join(',')
      tempData.user = data.realname
      tempData.userId = data.userId
      this._allotItems(tempData)
    },
    _allotItems: async function(data) {
      const result = await soilTest.allotExp(data)
      if (result) {
        this._resultChange('分配成功')
      }
    },
    // 样品详情
    _sampleDetail(data) {
      this.$nextTick(function() {
        if (data.type === 1) {
          this.currentComponent = 'FoodSampleGovernDetail'
          this.$store
            .dispatch('FoodSample/getByGovernId', data.sampleId)
            .then(() => {
              this.$refs.refModal._open(
                this.$store.state.FoodSample.governModel
              )
            })
        } else {
          this.currentComponent = 'FoodSampleCompanyDetail'
          this.$store
            .dispatch('FoodSample/getByCompanyId', data.sampleId)
            .then(() => {
              this.$refs.refModal._open(
                this.$store.state.FoodSample.companyModel
              )
            })
        }
        this.$refs.refModal._open(data.sampleId)
      })
    },
    _clearAll() {
      this.getPage.records = []
      this.selectIds = []
    }
  }
}
</script>
