<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.name" @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" :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.key==='status'">{{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>
    <IndexManage ref="indexModal" @on-result-change="_page"></IndexManage>
    <Reason ref="reasonModal" @on-result-change="_reasonResult"></Reason>
    <EquipManage ref="equipModal" @on-result-change="_page"></EquipManage>
  </div>
</template>
<script>
import Global from '../../../../api/config'
import { soilReport, soilTest } from '../../../../api'
import AssignPerson from '../../../../components/user-info-single/assignPerson'
import IndexManage from '../IndexManage'
import Reason from '../../../../components/base/Reason'
import EquipManage from '../EquipManage'
export default {
  components: { AssignPerson, IndexManage, Reason, 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: 'check-sample-right-submit', name: '提交' },
        { type: 'warning', id: 'check-sample-right-back', name: '退回' }
      ],
      getPage: {},
      iconMsg: [
        {
          type: 'ios-book',
          id: 'check-sample-right-record',
          name: '查看原始记录'
        },
        { type: 'md-apps', id: 'check-sample-right-view', name: '查看指标' },
        { type: 'ios-flask', id: 'check-sample-right-equip', name: '设备列表' }
      ],
      pageColumns: [
        { title: '试验名称', key: 'name', width: 160 },
        { title: '试验项目英文简写', key: 'shortName', width: 140 },
        { title: '大类', key: 'mainType', width: 140 },
        { title: '小类', key: 'smallType', width: 140 },
        { title: '检测依据', key: 'testBasis', width: 180 },
        { title: '试验方法', key: 'testMethod', width: 180 },
        { title: '状态', key: 'status', width: 180 }
      ],
      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)
    },
    _reasonResult(data) {
      if (undefined !== data && data !== '') {
        this._reportCheckBack(data)
      }
    },
    _reportCheckBack: async function(data) {
      const result = await soilTest.checkBack({
        ids: this.selectIds.join(','),
        remark: data
      })

      if (result) {
        this._resultChange('退回成功')
      }
    },
    _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')
      this.selectIds = []
    },
    async _btnClick(msg) {
      switch (msg) {
        case '试验项目分配':
          this._userAssign()
          break
        case '按组分配':
          await this._reportDueDate()
          await this._groupAssign()
          break
        case '提交':
          this._submitToAudit()
          break
        case '退回':
          this._checkBack()
          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
      }
    },
    _submitToAudit() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据')
      } else {
        this.$Modal.confirm({
          title: '提示',
          content: '确定提交该数据？',
          onOk: () => {
            this._submitToAuditOk()
          }
        })
      }
    },
    _submitToAuditOk: async function() {
      const result = await soilTest.endExpCheck({
        ids: this.selectIds.join(',')
      })
      if (result) {
        this._resultChange('提交成功')
      }
    },
    _checkBack() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据')
      } else {
        this.$refs.reasonModal._open('退回原因')
      }
    },
    // 信息维护
    _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.pageCheck(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()
          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 '查看原始记录':
            if (data.recorded === '是') {
              this._recordLook(data)
            } else {
              this.$Message.warning('尚未填写原始记录')
            }
            break
          case '查看指标':
            this._indexManage(data)
            break
          case '设备列表':
            this._equipManage(data)
            break
        }
      })
    },
    _recordLook(data) {
      if (data.objectKey) {
        this._reportMakeLook(data)
      } else {
        this._viewRecord(data.recordId)
      }
    },
    _reportMakeLook: async function(data) {
      const result = await soilReport.getExcelOriginalRecord(data.id)
      if (result) {
        this._viewReport(result)
      }
    },
    _viewReport(data) {
      if (data) {
        this.$openWindowModeless({
          objectKey: data.objectKey,
          idType: 10,
          id: data.id,
          isReport: 4
        })
      }
    },
    _equipManage(data) {
      this.$refs.equipModal._open(data)
    },
    _indexManage(data) {
      this.$refs.indexModal._open(data)
    },
    _viewRecord(originalRecordId) {
      // 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/' + originalRecordId + '?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')
      })
    },
    _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('分配成功')
      }
    },
    _clearAll() {
      this.getPage.records = []
      this.selectIds = []
    }
  }
}
</script>
