<template>
  <div>
    <Row>
      <!--查询-->
      <Col span="24" />
      <Form
        v-show="searchOpen"
        inline
        onsubmit="return false"
        :label-width="70"
        class="search-form"
      >
        <label class="label-sign" />
        <Form-item class="search-item" label="项目名称:">
          <Input v-model="formObj.name" placeholder="请输入项目名称" clearable @on-enter="_formSearch" />
        </Form-item>
        <Form-item class="search-btn">
          <Button type="primary" @click="_formSearch">
            搜索
          </Button>
        </Form-item>
      </Form>
      </Col>
      <!--按钮-->
      <!--按钮-->
      <Col span="24" />
      <Button type="success" style="margin-bottom: 12px" @click="_addConsume">
        添加耗材
      </Button>
      <Button type="success" style="margin-bottom: 12px" @click="_deleteSelected">
        移除
      </Button>
      </Col>
      <!--table-->
      <Col span="24" />
      <element-table
        ref="pageTable"
        :page-columns="pageColumns"
        :table-height="tableHeight"
        :get-page="getPage"
        :opt-col-width="140"
        :icon-msg="iconMsg"
        show-check-box
        @on-result-change="_tableResultChange"
      >
        <el-table-column
          v-for="item in pageColumns"
          :key="item.key"
          show-overflow-tooltip
          sortable
          :prop="item.key"
          :label="item.title"
          :width="item.width"
          :min-width="200"
          :fixed="item.fixed?item.fixed:undefined"
        >
          <template slot-scope="scope">
            <div v-if="item.dateTime">
              {{ scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd HH:MM:ss'):'' }}
            </div>
            <span v-else-if="item.type" class="blue-color">
              {{ scope.row[item.key] === undefined ? '': scope.row[item.key].display }}
            </span>
            <span v-else-if="item.isNot" class="blue-color">
              {{ scope.row[item.key] === 0 ? '否': '是' }}
            </span>
            <div v-else>
              {{ scope.row[item.key] }}
            </div>
          </template>
        </el-table-column>
      </element-table>
      </Col>
    </Row>
    <assign-person ref="assignPersonModal" is-change @on-result-change="_userResult" />

    <!--退回原因-->
    <reasonEdit ref="reasonModal" @on-result-change="_reasonResult" />


    <!--选择耗材-->
    <LmsConsumeSelect ref="consumeSelectModal" @on-result-change="_page" />
  </div>
</template>
<script>
import { consumeLedger, consumeClassify } from '../../../api'
import assignPerson from '../../../components/user-info-single/assignPerson'
import reasonEdit from '../../../components/base/Reason'
import LmsConsumeSelect from './LmsConsumeSelect'
export default {
  components: {
    assignPerson,
    reasonEdit,
    LmsConsumeSelect
  },
  data() {
    return {
      formObj: {
        name: '',
        classifyId: ''
      },
      submitData: {
        // 要提交至归类的数据
        classifyId: '',
        chemicalIds: []
      },
      searchOpen: true,
      btn: [
        { type: 'success', id: '', name: '添加耗材' },
        { type: 'success', id: '', name: '移除' }
      ],
      pageColumns: [
        { title: '耗材编号', width: 100, key: 'num' },
        {
          title: '耗材名称',
          key: 'name',
          width: 140,
          align: 'left'
        },
        { title: '耗材类别', width: 140, key: 'category' },
        { title: '库存量', width: 100, key: 'stock' },
        { title: '计量单位', width: 100, key: 'unit' },
        { title: '转化率', width: 100, key: 'exchange' },
        { title: '转化单位', width: 100, key: 'exunit' },
        { title: '转化库存量', width: 130, key: 'exstock' },
        { title: '仓库位置', width: 150, key: 'storehouse' },
        { title: '等级（纯度）', width: 130, key: 'quality' },
        { title: '规格', width: 100, key: 'spec' },
        { title: '制造厂商', width: 200, key: 'manufacturer' },
        { title: '密度', width: 100, key: 'thickness' },
        { title: '精确度等级', width: 130, key: 'unsure' },
        { title: '标准值', width: 100, key: 'standard' },
        { title: '备注', width: 140, key: 'remark' }
      ],
      getPage: {},
      sampleIds: [],
      classifyId: '',
      selectIds: [], // 检测项目id
      iconMsg: [
        // { type: 'pt-a-edit', id: '', name: '编辑' },
        // { type: 'pt-a-trash', id: '', name: '删除' }
      ],
      iconMsgDis: [
        // { type: 'pt-a-edit', id: '', name: '编辑' },
        // { type: 'pt-a-trash', id: '', name: '删除', disabled: true }
      ]
    }
  },
  computed: {
    tableHeight: function() {
      if (this.searchOpen) {
        return this.$tableHeight('search') - 60
      } else {
        return this.$tableHeight('noSearch') - 60
      }
    }
  },
  mounted() {
    this._page()
  },
  methods: {
    _formSearch() {
      if (this.sampleIds.length !== 0 || this.getPage.records === []) {
        this.$refs.pageTable._pageChange(1)
      }
    },
    _init() {
      this.getPage.records = []
      this.$refs.pageTable._initTable()
    },
    _submitCheck() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        this.$Modal.confirm({
          title: '提示',
          content: '确定提交该数据？',
          loading: true,
          onOk: () => {
            this._submitOk(this.selectIds)
          }
        })
      }
    },
    _submitOk: async function(id) {
      if (!id.length) return false
      const result = await consumeLedger.submitCheck(id)
      if (result) {
        this.$Modal.remove()
        this.$Message.success('提交成功!')
        this.$emit('on-result-change')
        this._page()
      }
    },

    _addConsume() {
      if (this.classifyId === undefined || this.classifyId === '') {
        this.$Message.warning('请选择归类!')
        return false
      }
      this.$refs.consumeSelectModal._open(this.classifyId)
    },
    _backCheck() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条数据！')
      } else {
        this.$Modal.confirm({
          title: '提示',
          content: '确定退回 ' + this.selectIds.length + ' 条记录？',
          onOk: () => {
            this.$refs.reasonModal._open('退回原因')
          }
        })
      }
    },
    _userResult: async function(data) {
      const tempData = {}
      tempData.userId = data.userId
      tempData.userName = data.realname
      const result = await consumeLedger.allocateItem({
        ids: this.selectIds.join(','),
        obj: tempData
      })
      if (result) {
        this.$Message.success('分配成功！')
        this._page()
      }
    },

    _page: async function() {
      if (this.classifyId === undefined || this.classifyId === '') {
        return false
      }
      this.getPage.records = []
      Object.assign(this.formObj, this.$refs.pageTable._searchParams())
      const result = await consumeLedger.pageIncludeClassify(
        this.$serializeForm(this.formObj)
      )
      if (result) {
        this.getPage = result
        this.$refs.pageTable._initTable()
      }
    },
    _searchParams(formId) {
      return this.$refs.pageTable._searchParams(formId)
    },
    _btnClick(msg, data) {
      if (msg === 'search') {
        this.searchOpen = !this.searchOpen
      }
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'page':
          this._page()
          break
        case 'iconClick':
          this._iconClick(data.name, data.rowData)
          break
        case 'selectIds':
          this.selectIds = data
          break
      }
    },

    _open(data) {
      if (undefined !== data && data.id !== undefined) {
        this.classifyId = data.id
        this.formObj.classifyId = data.id
        this._page()
      } else {
        this.sampleIds = []
        this.getPage.records = []
      }
    },

    _deleteSelected() {
      // 批量删除
      const ids = this.selectIds
      if (ids === '') {
        this.$Message.warning('请选择一条或多条数据！')
      } else {
        this._deleteById(ids, '确定移除 ' + ids.length + ' 条记录？')
      }
    },

    _iconClick(res, data) {
      switch (res) {
        case '编辑':
          this._editModal(data.id)
          break
        case '删除':
          this._deleteById(data.id)
          break
      }
    },
    // 删除
    _deleteById(id) {
      this.$Modal.confirm({
        title: '提示',
        content: '确定删除该信息？',
        onOk: () => {
          this._delOk(id)
        }
      })
    },
    _delOk: async function(id) {
      this.submitData.chemicalIds = id
      this.submitData.classifyId = this.classifyId
      const result = await consumeClassify.removeClassifyConsume(
        this.submitData
      )
      if (result) {
        this.$Message.success('删除成功')
        this._page()
      }
    },
    _editModal: async function(id) {
      const result = await consumeLedger.getById(id)
      if (result) {
        this.$refs.editModal._open(result)
      }
    },
    _reasonResult: async function(data) {
      const result = await consumeLedger.backCheck({
        remark: data,
        ids: this.selectIds
      })
      if (result) {
        this.$Message.success('退回成功')
        this.$emit('on-result-change')
        this._page()
      }
    }
  }
}
</script>
