<template>
  <div>
    <Modal v-model="fillSampleModal" :mask-closable="false" width="1350" :styles="{marginTop:'-90px'}" @on-cancel="_cancel">
      <p slot="header">
        填写结果
      </p>
      <Row>
        <!--查询-->
        <Col span="24" />
        <Form v-show="searchOpen" inline onsubmit="return false" :label-width="90">
          <label class="label-sign" />
          <Form-item class="search-item" label="检测项目:">
            <Input v-model="formObj.name" placeholder="请输入检测项目" clearable @on-enter="_formSearch" />
            <input v-model="formObj.sampleId" type="hidden">
          </Form-item>
          <Form-item label="检测类型:" class="search-item" prop="type">
            <Input v-model="formObj.type" placeholder="请输入检测类型" clearable @on-enter="_formSearch" />
            <!--<el-select v-model="formObj.type" placeholder="请输入检测类型" size="small" style="width:100%">-->
            <!--<el-option-->
            <!--v-for="item in typeList"-->
            <!--:key="item.value"-->
            <!--:label="item.label"-->
            <!--:value="item.value"-->
            <!--/>-->
            <!--</el-select>-->
          </Form-item>
          <Form-item class="search-item" label="检测人:">
            <Input v-model="formObj.mobile" placeholder="请输入检测人" clearable @on-enter="_formSearch" />
          </Form-item>
          <Form-item class="search-item" label="分配时间:">
            <Date-picker
              type="daterange"
              split-panels
              style="width:100%;"
              placeholder="请选择分配时间"
              :editable="false"
              @on-change="_assignDateChange"
            />
            <input v-model="formObj.assignDateBegin" type="hidden" name="assignDateBegin">
            <input v-model="formObj.assignDateEnd" type="hidden" name="assignDateEnd">
          </Form-item>
          <Form-item class="search-btn">
            <Button type="primary" @click="_formSearch">
              搜索
            </Button>
          </Form-item>
        </Form>
        </Col>
        <!--操作-->
        <Col span="24" />
        <Button style="margin-bottom: 5px" type="primary" @click="_submit">
          确认
        </Button>
        <Button style="margin-bottom: 5px" type="primary" @click="_judge">
          判定
        </Button>
        <Button style="margin-bottom: 5px" type="primary" @click="_detectionValue">
          填写检测值
        </Button>
        <Button style="margin-bottom: 5px" type="primary" @click="_selectEquipmentByIds">
          选择仪器设备
        </Button>
        </Col>
        <!-- 表格 -->
        <Col span="24" />
        <element-table
          ref="pageTable"
          :get-page="getPage"
          :table-height="tableHeight"
          warn-key="manualJudge"
          is-data-input
          select-data
          show-check-box
          @on-result-change="_tableResultChange"
        >
          <el-table-column
            v-for="item in pageColumns"
            :key="item.id"
            show-overflow-tooltip
            :prop="item.key"
            :label="item.title"
            :min-width="item.width"
            :fixed="item.fixed?item.fixed:undefined"
          >
            <template slot-scope="scope">
              <span
                v-if="item.key==='testValue'"
                @click.stop="_handleRow(scope)"
              >
                <el-input
                  v-model="scope.row.testValue"
                  size="medium"
                  placeholder="请输入检测结果"
                  @blur="_handleTestValueEdit(scope.row.id,scope.row.testValue)"
                />
              </span>

              <span v-else-if="item.key==='sampleQuantity'" @click.stop="_handleRow(scope)">
                <el-input
                  v-model="scope.row.sampleQuantity"
                  size="medium"
                  placeholder="请输入样品量"
                  @blur="_handleSampleQuantityEdit(scope.row.id,scope.row.sampleQuantity)"
                />
              </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.key==='progress'">
                {{ scope.row[item.key]===undefined?'':scope.row[item.key].display }}
              </span>
              <span v-else-if="item.key==='singleJudge'">
                {{ scope.row[item.key]===undefined?'':scope.row[item.key].display }}
              </span>
              <span v-else-if="item.key==='judged'">
                {{ scope.row[item.key]===1?'是':'否' }}
              </span>
              <span v-else-if="item.key==='recordWriiten'">
                {{ scope.row[item.key]==='t'?'是':'否' }}
              </span>
              <span v-else>{{ scope.row[item.key] }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            :width="120"
            fixed="right"
          >
            <template slot-scope="scope">
              <icon-list
                :msg="iconMsgDised"
                :row-data="scope.row"
                @on-result-change="_iconClick"
              />
            </template>
          </el-table-column>
        </element-table>
        </Col>
      </Row>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult" />
      </div>
    </Modal>
    <!--判定-->
    <Judge ref="judgeModal" @on-result-change="_page" />
    <!--填写检测值-->
    <fillTestValue ref="valueModal" @on-result-change="_page" />
    <!--偏离申请-->
    <applyManage ref="applyModal" @on-result-change="_page" />
    <!--选择原始记录模板-->
    <originalRecordRecord ref="originalModal" @on-result-change="_originalRecordModelResult" />
    <!--填写原始记录模板-->
    <itemOriginalRecord ref="itemOriginalRecordModal" @on-result-change="_resultRecord" />
    <!--追填原始记录模板-->
    <itemAppendOriginalRecord ref="itemAppendOriginalRecordModal" @on-result-change="_resultRecord" />
    <!--选择追填原始记录模板-->
    <appendOriginalRecord ref="appendOriginalRecordModal" @on-result-change="_appendOriginalRecordModalResult" />
    <!--查看原始记录-->
    <itemOriginalRecordLook ref="itemOriginalRecordLookModal" @on-result-change="_formSearch" />
    <!--选择仪器设备-->
    <selectEquipItem ref="selectEquipItemModal" @on-result-change="_formSearch" />
    <!--查看仪器设备-->
    <equipmentDetail ref="detailModal" @on-result-change="_formSearch" />
    <!--检测值扩展-->
    <testValueExtend ref="testValueExtendModal" @on-result-change="_formSearch" />
  </div>
</template>
<script>
import { drugItem } from '../../../api'
import Judge from './Judge'
import fillTestValue from './fillTestValue'
import applyManage from './applyManage'
import originalRecordRecord from './origin/originalRecordRecord'
import itemOriginalRecord from './origin/itemOriginalRecord'
import itemAppendOriginalRecord from './origin/itemAppendOriginalRecord'
import itemOriginalRecordLook from './origin/itemOriginalRecordLook'
import appendOriginalRecord from './origin/appendOriginalRecord'
import selectEquipItem from './select-equip/selectEquipItem'
import equipmentDetail from './select-equip/equipmentDetail'
import testValueExtend from './test-value-extend/testValueExtend'

export default {
  components: {
    Judge,
    fillTestValue,
    applyManage,
    originalRecordRecord,
    itemOriginalRecord,
    itemAppendOriginalRecord,
    itemOriginalRecordLook,
    appendOriginalRecord,
    selectEquipItem,
    testValueExtend,
    equipmentDetail
  },
  data() {
    return {
      formObj: {
        name: '',
        type: '',
        sampleId: '',
        assignDateBegin: '',
        assignDateEnd: ''
      },
      typeList: [
        { label: '进场原料', value: 'ORIGINAL' },
        { label: '其他报检', value: 'OTHER' }
      ],
      searchOpen: false,
      btn: [
        { type: 'primary', id: '', name: '确认' },
        { type: 'primary', id: '', name: '判定' },
        { type: 'primary', id: '', name: '填写检测值' },
        { type: 'primary', id: '', name: '选择仪器设备' }
      ],
      footerList: [
        { id: '', type: '', name: '取消' },
        { id: '', type: 'primary', name: '确定' }
      ],
      currentRow: {},
      fillSampleModal: false,
      getPage: {},
      pageColumns: [
        { title: '检测项目', key: 'name', width: 120, fixed: true },
        { title: '检测类型', key: 'type', width: 150 },
        { title: '样本编号', key: 'sampleCode', width: 150 },
        { title: '样品量', key: 'sampleQuantity', width: 130 },
        { title: '检测结果', key: 'testValue', width: 160 },
        { title: '不合格数量', key: 'failQuantity', width: 160 },
        { title: '标偏', key: 'deviation', width: 160 },
        { title: '缺陷', key: 'defects', width: 160 },
        { title: '限值', key: 'limitValue', width: 130 },
        { title: '比较符', key: 'compareSymbol', width: 160 },
        { title: '单位', key: 'unit', width: 100 },
        { title: '是否系统判定', key: 'judged', width: 120, judged: true },
        { title: '排序', key: 'orderBy', width: 80, judged: true },
        { title: '状态', key: 'progress', width: 120, status: true },
        {
          title: '判定结果',
          key: 'singleJudge',
          width: 140,
          singleJudge: true
        },
        // { title: '是否填写原始记录', key: 'recordWriiten', width: 160 },
        { title: '仪器设备', key: 'equipNames', width: 160 },
        { title: '检测类型', key: 'category', width: 130 },
        { title: '检测依据', key: 'code', width: 140 },
        { title: '检测依据名称', key: 'standardName', width: 200 },
        { title: '检测科室', key: 'groupName', width: 150 },
        { title: '检测人', key: 'tester', width: 130 },
        { title: '录入时间', key: 'testDate', width: 130, date: true },
        { title: '分配时间', key: 'assignDate', width: 160, date: true },
        { title: '备注', key: 'remark', width: 120 }
      ],
      iconMsgDised: [
        { type: 'pt-a-edit', id: 'pt-a-input-extend', name: '检测结果扩展' },
        { type: 'pt-a-submit', id: '', name: '确认' }
      ],
      selectIds: [],
      selectData: [],
      status: true,
      singleStatus: false,
      proStatus: false,
      original: false
    }
  },
  computed: {
    tableHeight: function() {
      if (this.searchOpen) {
        return this.$tableHeight('', 294)
      } else {
        return this.$tableHeight('search')
      }
    }
  },
  methods: {
    // 分配时间
    _assignDateChange(data) {
      this.formObj.assignDateBegin = data[0]
      this.formObj.assignDateEnd = data[1]
    },
    _footerResult(msg, data) {
      switch (msg) {
        case '取消':
          this._cancel()
          break
        case '确定':
          this._cancel()
          break
      }
    },
    _cancel() {
      this.$emit('on-result-change')
      this.fillSampleModal = false
    },
    _hideLoading() {
      this.$refs.footerModal._hideLoading()
    },
    _open(id) {
      this.formObj.sampleId = id
      this._page()
      this.fillSampleModal = true
      this._hideLoading()
    },
    _page: async function() {
      Object.assign(this.formObj, this.$refs.pageTable._searchParams())
      const result = await drugItem.pageItemInput(
        this.$serializeForm(this.formObj)
      )
      if (result) {
        this.getPage = result
        this.$refs.pageTable._initTable()
      }
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'page':
          this._page()
          break
        case 'selectData':
          this._selectData(data)
          break
        case 'iconClick':
          this._iconClick(data.name, data.rowData)
          break
      }
    },
    _selectData(data) {
      this.status = true
      this.original = false
      const selectIds = []
      this.selectData = data
      data.forEach(v => {
        if (
          v.status.display === '已录入' ||
          v.status.display === '取制样录入' ||
          v.status.display === '取制样偏离申请中' ||
          v.status.display === '取制样偏离驳回' ||
          v.status.display === '偏离驳回' ||
          v.status.display === '偏离申请中'
        ) {
          this.status = false
        }
        if (v.recordWriiten === 't') {
          this.original = true
        }
        selectIds.push(v.id)
      })
      this.selectIds = selectIds
    },
    _formSearch() {
      this.$refs.pageTable._pageChange(1)
    },
    // 追填原始记录 回调
    _resultRecord() {
      this._formSearch()
      this.$emit('on-result-change')
    },
    _btnClick(msg) {
      switch (msg) {
        case '判定':
          this._judge()
          break
        case '填写检测值':
          this._detectionValue()
          break
        case '确认':
          this._submit()
          break
        case '选择原始记录模板':
          this._changeOriginalRecord()
          break
        case '追填原始记录':
          this._appendOriginalRecord()
          break
        case '选择仪器设备':
          this._selectEquipmentByIds()
          break
        case 'search':
          this.searchOpen = !this.searchOpen
          break
      }
    },
    // 选择原始记录模板
    _changeOriginalRecord() {
      const ids = this.selectIds
      if (ids.length === 0) {
        this.$Message.warning('请至少选择一条数据!')
      } else if (this.original && this.status) {
        this.$Message.warning('已有原始记录模板，不可以再次选择!')
      } else if (this.status) {
        this.$refs.originalModal._open(ids, this.selectData)
      } else {
        this.$Message.warning('选择的数据已经提交,请发起偏离申请后再修改!')
      }
    },
    _originalRecordModelResult(data) {
      if (data) {
        this.$refs.itemOriginalRecordModal._open(
          this.selectIds,
          data.modelId.id,
          data.dataSource
        )
      } else {
        const ids = this.selectIds
        if (ids.length === 0) {
          this.$Message.warning('请至少选择一条数据!')
        } else {
          this._appendOriginalRecord()
        }
      }
    },
    // 追填原始记录
    _appendOriginalRecord() {
      const ids = this.selectIds
      if (ids.length === 0) {
        this.$Message.warning('请至少选择一条数据!')
      } else if (!this.original && this.status) {
        this.$Message.warning('未填写过原始记录，请先选择模板!')
      } else if (this.status) {
        this.$refs.appendOriginalRecordModal._open(ids)
      } else {
        this.$Message.warning('选择的数据已经提交,请发起偏离申请后再修改!')
      }
    },
    // 选择追填原始记录
    _appendOriginalRecordModalResult(data) {
      this.$refs.itemAppendOriginalRecordModal._open(
        this.selectIds,
        data.recordId
      )
    },
    // 批量确认
    _submit() {
      if (this.selectData.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        this.$Modal.confirm({
          title: '提示',
          content: '确定该操作？',
          onOk: async () => {
            this.selectIds = []
            for (let i = 0; i < this.selectData.length; i++) {
              this.selectIds.push(this.selectData[i].id)
            }
            const result = await drugItem.bathConfirmItem(this.selectIds)
            if (result) {
              this.$Message.success('提交成功')
              this.selectIds = []
              this._page()
            }
          }
        })
      }
    },
    _submitById(id) {
      this.$Modal.confirm({
        title: '提示',
        content: '确定该操作？',
        onOk: async () => {
          const result = await drugItem.bathConfirmItem(id)
          if (result) {
            this.$Message.success('提交成功')
            this._page()
          }
        }
      })
    },
    // 批量判定
    _judge() {
      if (this.selectData.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        this.selectIds = []
        for (let i = 0; i < this.selectData.length; i++) {
          this.selectIds.push(this.selectData[i].id)
        }
        this.$refs.judgeModal._open(this.selectIds)
      }
    },

    _testValueExtend(itemId) {
      this.$refs.testValueExtendModal._open(itemId)
    },

    // 批量填写检测值
    _detectionValue() {
      if (this.selectData.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else if (this.status) {
        this.selectIds = []
        for (let i = 0; i < this.selectData.length; i++) {
          this.selectIds.push(this.selectData[i].id)
        }
        this.$refs.valueModal._open(this.selectIds)
      } else {
        this.$Message.warning('您选择状态不可填写检测结果,请重新选择！')
      }
    },
    // 批量选择仪器设备
    _selectEquipmentByIds() {
      const ids = this.selectIds
      if (ids.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        this._selectEquipment(ids)
      }
    },
    _iconClick(res, data) {
      switch (res) {
        case '查看原始记录':
          this._itemOriginalRecordLook(data, 'only')
          break
        case '编辑原始记录':
          this._itemOriginalRecordLook(data, 'write')
          break
        case '确认':
          this._submitById(data.id)
          break
        case '检测结果扩展':
          this._testValueExtend(data.id)
          break
        case '偏离申请':
          this._skewingApply(data)
          break
        case '查看仪器设备':
          this._checkEquipment(data.id)
          break
      }
    },
    // 查看仪器
    _checkEquipment(id) {
      this.$refs.detailModal._open(id)
    },
    // 查看原始记录
    _itemOriginalRecordLook(data, name) {
      if (
        data.recordId === null ||
        undefined === data.recordId ||
        data.recordId === ''
      ) {
        this.$Message.warning('该检测项目暂无原始记录！')
      } else {
        this.$refs.itemOriginalRecordLookModal._open(
          data.recordId,
          name,
          data.id
        )
      }
    },
    // 选择仪器设备
    _selectEquipment(ids) {
      this.$refs.selectEquipItemModal._open(ids)
    },
    _skewingApply(data) {
      this.$refs.applyModal._open(data)
    },
    // 操作的序号
    _handleRow(data) {
      this.currentRow = data.row
    },
    // 单个填写检测值
    _handleTestValueEdit: async function(id, testValue) {
      if (testValue !== '' && undefined !== testValue) {
        const data = {}
        data.itemIds = id
        data.testValue = testValue
        const result = await drugItem.testValue(data)
        if (result) {
          this.$Message.success('保存成功')
          this._page()
        } else {
          this.$Message.error('保存失败')
        }
      }
    },

    _handleSampleQuantityEdit: async function(id, sampleQuantity) {
      if (sampleQuantity !== '' && undefined !== sampleQuantity) {
        const data = {}
        data.itemIds = id
        data.sampleQuantity = sampleQuantity
        const result = await drugItem.edit(data)
        if (result) {
          await this._page()
        } else {
          this.$Message.error('保存失败')
        }
      }
    },
    _handleOrderByValueEdit: async function(id, orderBy) {
      if (orderBy !== '' && undefined !== orderBy) {
        const data = {}
        data.itemIds = id
        data.orderBy = orderBy
        const result = await drugItem.orderByChange(data)
        if (result) {
          this._page()
        } else {
          this.$Message.error('保存失败')
        }
      }
    }
  }
}
</script>
