<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" :page-columns="pageColumns" :table-height="tableHeight"
                    :get-page="getPage" :table-name="tableName"  @on-result-change="_tableResultChange" 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" :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>
  </div>
</template>
<script>
import Global from '../../../../../api/config'
import { soilTest } from '../../../../../api'
import AssignPerson from '../../../../../components/user-info-single/assignPerson'
export default {
  components: { AssignPerson },
  data() {
    return {
      // 定义表格名称----英文
      tableName: 'food-task-assign-item-right',
      formObj: {
        sampleCode: undefined
      },
      // 用户自己选中的列
      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: 'allot-task-sample-adjust-his-sample',
          name: '调整试验项目检测人'
        }
      ],
      getPage: {},
      pageColumns: [
        { title: '试验名称', key: 'name', width: 160 },
        { title: '试样编号', key: 'sampleCode', width: 160 },
        { title: '试验人员', key: 'tester', width: 180 },
        { title: '分配人', key: 'alloter', width: 160 },
        { title: '分配时间', key: 'allotTime', width: 160, datetime: true },
        { 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)
    },
    _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 '调整分组':
          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
      }
    },
    // 信息维护
    _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(data) {
      this.getPage.records = []
      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()
      }
    },
    _clearAll() {
      this.getPage.records = []
      this.selectIds = []
    },
    _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.pageAllotHis(
        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 'table-col':
          // 用户选中的表格列
          this.userColumns = data
          break
        case 'changeSize':
          this._page()
          // this.$refs.pageTable._checkAll()
          break
      }
    },
    // 按人分配  选人选时间
    _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')
      })
    },
    _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.changeExpAllot(data)
      if (result) {
        this._resultChange('分配成功')
      }
    }
  }
}
</script>
