<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 v-model="formObj.sampleCode" name="sampleCode" placeholder="请输入试样编号" clearable @on-enter="_formSearch"></Input>
          </Form-item>
          <Form-item class="search-btn">
            <Button type="primary" @click="_formSearch">搜索</Button>
          </Form-item>
        </Form>
      </Col>
      <!--操作-->
      <Col span="24">
        <btn-list :msg="btn" class="contHide" @on-result-change="_btnClick"></btn-list>
      </Col>
      <!-- 表格 -->
      <Col span="24">
        <PTVXETable ref="pageTable" :page-columns="pageColumns" :table-height="tableHeight"
                    :get-page="getPage" :icon-msg="iconMsg" :table-name="tableName" is-task  select-data @on-result-change="_tableResultChange">
          <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>{{scope.row[item.key]}}</span>
            </template>
          </vxe-table-column>
          <VXESettingCol slot="setting" :page-columns="pageColumns" :user-columns="userColumns"
                         :table-name="tableName" @on-result-change="_resetColumn"></VXESettingCol>
        </PTVXETable>
      </Col>
    </Row>
    <AssignPerson ref="personModal" @on-result-change="_assignBackData"></AssignPerson>
<!--    <SelectOriTempRecord ref="recordModal" @on-result-change="_page"></SelectOriTempRecord>-->
<!--    <OriginalRecordEdit ref="editModal"></OriginalRecordEdit>-->
    <EquipManage ref="equipModal" @on-result-change="_page"></EquipManage>
    <IndexManage ref="indexModal" @on-result-change="_page"></IndexManage>
    <Reason ref="reasonModal" @on-result-change="_reasonResult"></Reason>
  </div>
</template>
<script>
import Global from '../../../../api/config'
import { soilReport, soilTest } from '../../../../api'
import AssignPerson from '../../../../components/user-info-single/assignPerson'
import EquipManage from '../EquipManage'
// import SelectOriTempRecord from '../SelectOriTempRecord'
// import OriginalRecordEdit from '../OriginalRecordEdit'
import IndexManage from '../IndexManage'
import Reason from '../../../../components/base/Reason'
export default {
  components: {
    AssignPerson,
    Reason,
    EquipManage,
    // SelectOriTempRecord,
    // OriginalRecordEdit,
    IndexManage
  },
  data() {
    return {
      // 定义表格名称----英文
      tableName: 'food-task-assign-item-right',
      formObj: {
        entrustId: '',
        name: '',
        testMethod: '',
        testBasis: '',
        obj: {
          entrustId: '',
          nameList: []
        }
      },
      entrustId: '',
      // 用户自己选中的列
      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: 'warning', id: '', 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: 'mainType', width: 140 },
        { title: '小类', key: 'smallType', width: 140 },
        { title: '原始记录是否填写', key: 'recorded', 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()
  },
  methods: {
    _reasonResult(data) {
      if (undefined !== data && data !== '') {
        this._reportCheckBack(data)
      }
    },
    _reportCheckBack: async function(data) {
      const result = await soilTest.auditBack({
        ids: this.selectIds.join(','),
        remark: data
      })

      if (result) {
        this._resultChange('退回成功')
      }
    },
    _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)
    },
    _auditBack() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据')
      } else {
        this.$refs.reasonModal._open('退回原因')
      }
    },
    _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)
              }
            }
          }
        }
      )
    },
    // 获取column
    _getColumn() {
      this.$refs.pageTable._getColByTableName()
    },
    // 重置column
    _resetColumn(colList) {
      this.userColumns = colList
      this.$refs.pageTable._loadColumn(colList)
    },
    _modalResult(data) {
      switch (this.currentComponent) {
        case 'AssignPerson':
          if (this.defaultPlanDate) {
            this._trueDefault(data)
          } else {
            this._userResult(data)
          }
          break
        case 'UserGroup':
          this._userGroupResult(data)
          break
        default:
          this._page()
      }
    },
    _resultChange(msg) {
      this.$Message.success(msg)
      this._page()
      this.$emit('on-result-change')
    },
    _btnClick(msg) {
      switch (msg) {
        case '按人分配':
          this._allotByPerson()
          // await this._reportDueDate()
          // await this._userAssign()
          break
        case '提交':
          this._submitToMake()
          break
        case '退回':
          this._auditBack()
          break
        case '试验项目分配':
          this._userAssign()
          break
        case '填写原始记录':
          this._addRecord()
          break
        case '调整分组':
          if (this.selectIds.length === 0) {
            this.$Message.warning('请至少选择=一条数据')
          } else {
            this.currentComponent = 'UserGroup'
            this.$nextTick(() => {
              this.$refs.refModal._open()
            })
          }
          break
      }
    },
    _submitToMake() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据')
      } else {
        this.$Modal.confirm({
          title: '提示',
          content: '确定提交该数据？',
          onOk: () => {
            this._submitToMakeOk()
          }
        })
      }
    },
    _submitToMakeOk: async function() {
      const result = await soilTest.endExpAudit({
        ids: this.selectIds.join(',')
      })
      if (result) {
        this._resultChange('提交成功')
      }
    },
    _addRecord() {
      if (this.selectIds.length === 0) {
        this.$message.warning('请至少选择一条数据')
      } else {
        console.log('打开填写原始记录界面')
        this.$refs.recordModal._open(this.selectIds, this.entrustId)
      }
    },
    _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() {
      this.formObj.obj.nameList = []
      Object.assign(this.formObj, this.$refs.pageTable._searchParams())
      this.formObj.obj.entrustId = this.entrustId

      console.log('-----this.leftSelectData-------', this.leftSelectData)
      this.formObj.obj.nameList = this.leftSelectData
      // alert(this.formObj.obj.nameList.length)
      // if (this.formObj.obj.nameList.length === 0) {
      //   return false
      // }
      const result = await soilTest.pageExperimentAuditBath(
        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')
    },
    // 遍历出计划时间为空的样品名
    _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>
