<template>
  <div>
    <Row>
      <!--查询-->
      <Col span="24">
        <Form id="task-assign-item-right" :label-width="70" inline onsubmit="return false">
          <label class="label-sign"></label>
          <Form-item class="search-item" label="检测项目:">
            <Input @on-enter="_formSearch" name="name" 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" :getPage="getPage" :icon-msg="iconMsg" :table-name="tableName"  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.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-if="item.key==='progress'">{{scope.row[item.key].display}}</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>
    <OriginalRecordEdit ref="editModal"></OriginalRecordEdit>
    <IndexManage ref="indexModal" @on-result-change="_page"></IndexManage>
    <EquipManage ref="equipModal" @on-result-change="_page"></EquipManage>
    <CollectManage ref="collectModal" @on-result-change="_page"></CollectManage>
    <CollectFileManage ref="collectFileModal" @on-result-change="_page"></CollectFileManage>
    <SelEquip ref="selEquip" @on-result-change="_equipResult"></SelEquip>
  </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 OriginalRecordEdit from '../OriginalRecordEdit'
import IndexManage from '../IndexManage'
import SelEquip from '../../../../components/select-equip/SelEquip'
import EquipManage from '../EquipManage'
import CollectManage from '../CollectManage'
import CollectFileManage from '../CollectFileManage'
export default {
  components: {
    AssignPerson,
    SelectOriTempRecord,
    OriginalRecordEdit,
    IndexManage,
    SelEquip,
    EquipManage,
    CollectManage,
    CollectFileManage
  },
  data() {
    return {
      // 定义表格名称----英文
      tableName: 'food-task-assign-item-right',
      formObj: {
        entrustId: '',
        name: '',
        testMethod: '',
        testBasis: ''
      },
      entrustId: '',
      envPro: false,
      // 用户自己选中的列
      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: '设备' }
      ],
      btnPro: [
        { type: 'success', id: '', name: '填写原始记录' },
        { type: 'success', id: '', name: '设备' },
        { type: 'success', id: '', name: '完成提交' }
      ],
      iconMsg: [
        { type: 'ios-book', id: '', name: '查看原始记录' },
        { type: 'md-apps', id: '', name: '查看指标' },
        { type: 'ios-bookmarks', id: '', name: '查看采集数据' },
        { type: 'ios-browsers', id: '', name: '查看采集文件' },
        { type: 'ios-flask', id: '', name: '设备列表' }
      ],
      getPage: {},
      pageColumns: [
        { title: '试验项目', key: 'name', width: 120, fixed: 'left' },
        { title: '试样编号', key: 'sampleCode', width: 180 },
        { title: '是否填写原始记录', key: 'recorded', width: 180 },
        { title: '试样深度', key: 'sampleDepth', width: 180 },
        { title: '试样包装类型', key: 'samplePack', 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: {},
      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()
    if (process.env.NODE_ENV === 'production') {
      this.envPro = true
    }
  },
  methods: {
    _iconClick(res, data, currentComponent) {
      this.$nextTick(() => {
        switch (res) {
          case '查看原始记录':
            console.log(data)
            if (data.recordId) {
              this._viewRecord(data.recordId)
            } else {
              this.$Message.warning('未填写原始记录')
            }
            break
          case '查看指标':
            this._indexManage(data)
            break
          case '查看采集数据':
            this._collectManage(data)
            break
          case '查看采集文件':
            this._collectFileManage(data)
            break
          case '设备列表':
            this._equipManage(data)
            break
        }
      })
    },
    _collectManage(data) {
      this.$refs.collectModal._open(data)
    },
    _collectFileManage(data) {
      this.$refs.collectFileModal._open(data)
    },
    _indexManage(data) {
      this.$refs.indexModal._open(data)
    },
    _equipManage(data) {
      this.$refs.equipModal._open(data)
    },
    _viewRecord(recordId) {
      console.log(recordId)
      // layx.iframe('labRecordWriteOriView', '原始记录预览', Global.recordURL + '/print/v1/form/' + originalRecordId, {
      let recordUrl = ''
      if (process.env.NODE_ENV === 'production') {
        recordUrl = 'http://record.patzn.com'
      } else {
        recordUrl = Global.recordURL
      }
      // eslint-disable-next-line no-undef
      layx.iframe(
        'labRecordWriteOriView',
        '原始记录预览',
        recordUrl + '/print/v1/form/' + recordId + '?type=ENVTESTMAKE',
        {
          event: {
            onload: {
              after: function(layxWindow, winform) {
                // eslint-disable-next-line no-undef
                layx.max(winform.id)
              }
            }
          }
        }
      )
    },
    // 获取column
    _getColumn() {
      this.$refs.pageTable._getColByTableName()
    },
    // 重置column
    _resetColumn(colList) {
      this.userColumns = colList
      this.$refs.pageTable._loadColumn(colList)
    },
    _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('添加成功')
      }
    },
    _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()
      }
    },
    // 设置时间
    _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')
        })
      }
    },
    _resultChange(msg) {
      this.$Message.success(msg)
      this._page()
      this.$emit('on-result-change')
    },
    async _btnClick(msg) {
      switch (msg) {
        case '按人分配':
          this._allotByPerson()
          // await this._reportDueDate()
          // await this._userAssign()
          break
        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 = []
        const clientInfo = []
        for (let i = 0; i < this.selectData.length; i++) {
          clientInfo.push(this.selectData[i].client)
          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('所选数据中有已填写原始记录的')
        } else {
          console.log('打开填写原始记录界面')
          this.$refs.recordModal._open(
            this.selectIds,
            this.entrustId,
            clientInfo
          )
        }
      }
    },
    _allotByPerson() {
      const user = Global.getUserInfo('userInfo')
      this.$refs.personModal._openGoupByUserId('分配人员', user.id, 'itemTree')
    },
    // 信息维护
    _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.leftSelectData = data
      this.entrustId = id
      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._formSearch()
      }
    },
    _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.entrustId = this.entrustId
      this.formObj.name = this.leftSelectData.name
      this.formObj.testMethod = this.leftSelectData.testMethod
      const result = await soilTest.pageExpPrepare(
        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 'iconClick':
          this._iconClick(data.name, data.rowData, data.componentName)
          break
        case 'selectData':
          for (let i = 0; i < data.length; i++) {
            selectIds.push(data[i].id)
          }
          this.selectIds = selectIds
          this.selectData = data
          break
        case 'table-col':
          // 用户选中的表格列
          this.userColumns = data
          break
        case 'changeSize':
          this._page()
          // this.$refs.pageTable._checkAll()
          break
      }
    },
    // 按人分配  选人选时间
    _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('分配成功')
      }
    },
    _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')
      })
    },
    _clearAll() {
      this.getPage.records = []
      this.selectIds = []
    }
  }
}
</script>
