<template>
  <div>
    <Modal v-model="showEditModal" :mask-closable="false" width="1200">
      <p slot="header">
        {{ modalTitle }}
      </p>
      <div>
        <Alert>
          <Form
            id="edit-form"
            ref="formObj"
            :model="formObj"
            :rules="ruleValidate"
            :label-width="90"
            inline
            class="coll-search"
          >
            <Form-item label="申请单编号" prop="num">
              <Input v-model="formObj.num" name="num" placeholder="请输入申请单编号" style="width:250px" /></Input>
            </Form-item>
            <Form-item label="申请原因" prop="applyReason">
              <Input v-model="formObj.applyReason" name="applyReason" placeholder="请输入申请原因" style="width:250px" /></Input>
            </Form-item>
            <Form-item label="备注" prop="remark">
              <Input v-model="formObj.remark" name="remark" placeholder="请输入备注" style="width:250px" /></Input>
            </Form-item>
          </Form>
        </Alert>
        <!--采购详情-->
        <Row>
          <Col span="24" style="margin-bottom: 10px;" class="btn-width" />
          <div>
            <Button type="success" @click="_editModal">
              添加
            </Button>
            <Button type="error" @click="_deleteSelected">
              删除
            </Button>
            <!-- <Button type="ghost" @click="_export" id="equip-purchase-export">导出</Button>-->
          </div>
          </Col>
          <!-- 表格 -->
          <Col span="24" style="margin-bottom: 10px" />
          <element-table
            ref="pageTable"
            :page-columns="pageColumns"
            :table-height="tableHeight"
            :get-page="getPage"
            :opt-col-width="80"
            @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"
              :min-width="item.width"
              :fixed="item.fixed?item.fixed:undefined"
            >
              <template slot-scope="scope">
                <!--<div v-if="item.detail"><a @click.stop="_detailModal(scope.row.id)">{{scope.row[item.key]}}</a></div>-->
                <!--<div>{{scope.row[item.key]}}</div>-->
                <div v-if="item.key==='name'" @click="_handleRow(scope)">
                  <AutoCompletes
                    :value="scope.row.name"
                    show-key="name"
                    placeholder="请输入仪器名称"
                    :down-data="nameList"
                    blur-val
                    :handle-obj="scope"
                    @on-result-change="_nameChange"
                  />
                </div>
                <div v-else-if="item.key==='spec'" @click="_handleRow(scope)">
                  <AutoCompletes
                    :value="scope.row.spec"
                    show-key="spec"
                    placeholder="请输入规格型号"
                    :down-data="specList"
                    blur-val
                    :handle-obj="scope"
                    @on-result-change="_specChange"
                  />
                </div>
                <div v-else-if="item.key==='counts'" @click="_handleRow(scope)">
                  <el-input
                    v-model="scope.row.counts"
                    placeholder="请输入数量"
                    size="small"
                    @blur="_counts"
                    @focus="_handleRow(scope)"
                  />
                </div>
                <div v-else-if="item.key==='supplierName'" @click="_handleRow(scope)">
                  <AutoCompletes
                    :value="scope.row.supplierName"
                    show-key="name"
                    placeholder="请输入或选择供应商"
                    :down-data="supplierNameList"
                    blur-val
                    :handle-obj="scope"
                    @on-result-change="_supplierName"
                  />
                </div>
                <div v-else-if="item.key==='productPlace'" @click="_handleRow(scope)">
                  <AutoCompletes
                    :value="scope.row.productPlace"
                    show-key="productPlace"
                    placeholder="请输入或选择制造厂商"
                    :down-data="productPlaceList"
                    blur-val
                    :handle-obj="scope"
                    @on-result-change="_productPlace"
                  />
                </div>
                <div v-else-if="item.key==='uses'" @click="_handleRow(scope)">
                  <AutoCompletes
                    :value="scope.row.uses"
                    show-key="purpose"
                    placeholder="请输入或选择用途"
                    :down-data="rangeList"
                    blur-val
                    :handle-obj="scope"
                    @on-result-change="_uses"
                  />
                </div>
                <div v-else-if="item.key==='remark'" @click="_handleRow(scope)">
                  <el-input
                    v-model="scope.row.remark"
                    placeholder="请输入备注"
                    size="small"
                    @blur="_remark"
                    @focus="_handleRow(scope)"
                  />
                </div>
                <div v-else-if="item.key==='relatedStandards'" @click="_handleRow(scope)">
                  <el-input
                    v-model="scope.row.relatedStandards"
                    placeholder="请输入相关标准"
                    size="small"
                    @blur="_relatedStandards"
                    @focus="_handleRow(scope)"
                  />
                </div>
                <div v-else-if="item.key==='price'" @click="_handleRow(scope)">
                  <el-input
                    v-model="scope.row.price"
                    placeholder="请输入价格"
                    size="small"
                    @blur="_priceChange"
                    @focus="_handleRow(scope)"
                  />
                </div>
              </template>
            </el-table-column>
          </element-table>
          </Col>
        </Row>
      </div>
      <div slot="footer" class="btn-width">
        <Button style="margin-left: 8px" @click="_cancel">
          取消
        </Button>
        <Button style="margin-left: 8px" @click="_ok(0)">
          草稿
        </Button>
        <Button type="primary" @click="_ok(1)">
          提交
        </Button>
      </div>
    </Modal>
    <!--添加仪器采购明细-->
    <LmsEquipPurchasedEdit ref="editModal" @on-result-change="_purchaseData" />
    <!--复制-->
    <LmsEquipPurchaseEditCopy ref="editCopyModal" @on-result-change="_purchaseData" />
    <!--选择审批人-->
    <AssignPerson ref="selectUser" @on-result-change="_userData" />
  </div>
</template>

<script>
/**
 * 添加编辑仪器采购订单表
 */
import { equipPurchaseDetail, equipPurchase, dict } from '../../../../api'
import AutoCompletes from '../../../../components/base/autoCompletes.vue'
import AssignPerson from '../../../../components/user-info-single/assignPerson'
import LmsEquipPurchasedEdit from '../detail/LmsEquipPurchaseDetailEdit.vue'
import LmsEquipPurchaseEditCopy from './LmsEquipPurchaseEditCopy.vue'

let charseName = false
let charseSpec = false
let charseSupplierName = false
let charseProductPlace = false
let charsePurpose = false
export default {
  components: {
    LmsEquipPurchasedEdit,
    LmsEquipPurchaseEditCopy,
    AutoCompletes,
    AssignPerson
  },
  data() {
    return {
      id: '',
      modalTitle: '',
      formObj: {
        name: '',
        applyReason: '',
        remark: ''
      },
      dataObj: {
        purchaseId: ''
      },
      purchaseId: '',
      ruleValidate: {
        // num: [{required: true, message: '申请单编号不能为空', trigger: 'blur'}],
        applyReason: [
          { required: true, message: '申请名称不能为空', trigger: 'blur' }
        ]
      },
      selectIds: [],
      getPageList: [],
      showEditModal: false,
      getPage: {
        records: []
      },
      pageColumns: [
        {
          title: '仪器名称',
          key: 'name',
          width: 200
        },
        {
          title: '规格型号',
          key: 'spec',
          width: 200
        },
        {
          title: '数量',
          key: 'counts',
          width: 160
        },
        {
          title: '供应商',
          key: 'supplierName',
          width: 200
        },
        {
          title: '制造厂商',
          key: 'productPlace',
          width: 200
        },
        {
          title: '用途',
          key: 'uses',
          width: 160
        },
        {
          title: '备注',
          key: 'remark',
          width: 160
        },
        { title: '相关标准', key: 'relatedStandards', width: 160 },
        { title: '单价', key: 'price', width: 160 }
      ],
      iconMsg: [
        { type: 'trash-a', id: 'sys-area-add', name: '移除' },
        { type: 'ios-copy', id: '', name: '复制' }
      ],
      nameList: [],
      specList: [],
      supplierList: [],
      supplierListTemp: [],
      productPlaceList: [],
      rangeList: [],
      supplierNameList: [],
      currentRow: {},
      currentIndex: -1,
      status: '',
      sendUserId: '',
      isApproval: ''
    }
  },
  computed: {
    tableHeight: function() {
      return '400'
    }
  },
  mounted() {},
  methods: {
    // 仪器名称
    _nameChange(msg, data, handleObj) {
      this._handleRow(handleObj)
      switch (msg) {
        case 'select':
          charseName = true
          this.currentRow.name = data.name
          this._blurSave(this.currentRow.id, data.name, 'name')
          break
        case 'query':
          charseName = false
          this.currentRow.name = data.name
          this._openSearchEquipName(this.currentRow.name)
          break
        case 'blur':
          if (!charseName) {
            this._blurSave(this.currentRow.id, this.currentRow.name, 'name')
            charseName = true
          }
          break
      }
    },
    // 规格型号
    _specChange(msg, data, handleObj) {
      this._handleRow(handleObj)
      switch (msg) {
        case 'select':
          charseSpec = true
          this.currentRow.spec = data.spec
          this._blurSave(this.currentRow.id, data.spec, 'spec')
          break
        case 'query':
          charseSpec = false
          this.currentRow.spec = data.spec
          this._openSearchSpecName(this.currentRow.spec)
          break
        case 'blur':
          if (!charseSpec) {
            this._blurSave(this.currentRow.id, this.currentRow.spec, 'spec')
            charseSpec = true
          }
          break
      }
    },
    // 数量
    _counts(event) {
      this.currentRow.counts = event.target.value
      this._blurSave(this.currentRow.id, event.target.value, 'counts')
    },
    // 供应商
    _supplierName(msg, data, handleObj) {
      this._handleRow(handleObj)
      switch (msg) {
        case 'select':
          charseSupplierName = true
          this.currentRow.supplierName = data.name
          this._blurSave(this.currentRow.id, data.name, 'supplierName')
          break
        case 'query':
          charseSupplierName = false
          this.currentRow.supplierName = data.name
          this._supplier(this.currentRow.supplierName)
          break
        case 'blur':
          if (!charseSupplierName) {
            this._blurSave(
              this.currentRow.id,
              this.currentRow.supplierName,
              'supplierName'
            )
            charseSupplierName = true
          }
          break
      }
    },
    // 制造厂商
    _productPlace(msg, data, handleObj) {
      this._handleRow(handleObj)
      switch (msg) {
        case 'select':
          charseProductPlace = true
          this.currentRow.productPlace = data.productPlace
          this._blurSave(this.currentRow.id, data.productPlace, 'productPlace')
          break
        case 'query':
          charseProductPlace = false
          this.currentRow.productPlace = data.productPlace
          this._supplier(this.currentRow.productPlace)
          break
        case 'blur':
          if (!charseProductPlace) {
            this._blurSave(
              this.currentRow.id,
              this.currentRow.productPlace,
              'productPlace'
            )
            charseProductPlace = true
          }
          break
      }
    },
    // 用途
    _uses(msg, data, handleObj) {
      this._handleRow(handleObj)
      switch (msg) {
        case 'select':
          charsePurpose = true
          this.currentRow.purpose = data.purpose
          this._blurSave(this.currentRow.id, data.purpose, 'uses')
          break
        case 'query':
          charsePurpose = false
          this.currentRow.purpose = data.purpose
          this._supplier(this.currentRow.purpose)
          break
        case 'blur':
          if (!charsePurpose) {
            this._blurSave(this.currentRow.id, this.currentRow.purpose, 'uses')
            charsePurpose = true
          }
          break
      }
    },
    // 备注
    _remark(event) {
      this.currentRow.remark = event.target.value
      this._blurSave(this.currentRow.id, this.currentRow.remark, 'remark')
    },
    // 相关标准
    _relatedStandards() {
      // this.currentRow.relatedStandards = event.target.value;
      this._blurSave(
        this.currentRow.id,
        this.currentRow.relatedStandards,
        'relatedStandards'
      )
    },
    // 价格
    _priceChange() {
      this._blurSave(this.currentRow.id, this.currentRow.price, 'price')
    },
    // 操作的序号
    _handleRow(data) {
      this.currentRow = data.row
      this.currentIndex = data.$index
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'page':
          break
        case 'selectIds':
          this.selectIds = data
          break
        case 'iconClick':
          this._iconClick(data.name, data.rowData)
          break
      }
    },
    _export() {
      this.$Modal.confirm({
        title: '提示',
        content: '确定导出该申请单',
        onOk: () => {
          // this.$store
          //   .dispatch('ReportExport/getById', 'equip-purchase-export')
          //   .then(() => {
          //     if (this.$store.state.ReportExport.model) {
          //       // window.open(this.$store.state.ReportExport.model + '&purchaseId=' + this.dataObj.purchaseId, '_blank');
          //     }
          //   })
        }
      })
    },
    // _supplierChange(msg, data) {
    //   switch (msg) {
    //     case 'select':
    //       this.formObj.supplierName = data;
    //       break;
    //     default:
    //       this.formObj.supplierName = data;
    //       this._supplier(data);
    //       break;
    //   }
    // },
    _supplier(name = '') {
      // 供应商
      // const data = {}
      // data.name = name
      // this.$store.dispatch('LmsSupplier/list', data).then(() => {
      //   const supplierList = this.$store.state.LmsSupplier.list
      //   this.supplierNameList = supplierList
      // })
    },
    _blurSave(ids, value, name) {
      // this.$store
      //   .dispatch('LmsEquipPurchase/editEquipColAll', {
      //     id: ids,
      //     obj: this.$serializeFormSearch(this.currentRow)
      //   })
      //   .then(() => {
      //     if (this.$store.state.LmsEquipPurchase.success) {
      //     }
      //   })
    },
    _iconClick(res, data) {
      switch (res) {
        case '移除':
          this._deleteById(data.id)
          break
        case '复制':
          this._copy(data)
          break
      }
    },
    _copy(data) {
      this.$refs.editCopyModal._open(data, this.dataObj.purchaseId)
    },
    _open(formObj) {
      this.showEditModal = true
      this.$refs.pageTable._hideLoading()
      if (undefined === formObj) {
        this.modalTitle = '添加仪器采购单申请'
        // this.$store.dispatch('LmsEquipPurchase/getTemp').then(() => {
        //   // 查询有没有添加但没有保存的数据
        //   this.dataObj.purchaseId = this.$store.state.LmsEquipPurchase.model.id
        //   this.getPage.records = this.$store.state.LmsEquipPurchase.model.lmsEquipPurchaseDetailVOList
        // })
        this._getTemp()
      } else {
        this.formObj = formObj
        this.id = formObj.id
        this.dataObj.purchaseId = formObj.id
        this.purchaseId = formObj.id
        this.getPage.records = formObj.lmsEquipPurchaseDetailVOList
        this.modalTitle = '编辑仪器采购单申请'
      }
      // this._openSearch()
      // this._supplier()
    },

    _getTemp: async function() {
      const result = await equipPurchase.getTemp()
      if (result) {
        this.dataObj.purchaseId = result.id
        this.purchaseId = result.id
        this.getPage.records = result.lmsEquipPurchaseDetailVOList
      }
    },

    _openSearch() {
      this._openSearchEquipName()
      this._openSearchSpecName()
      this._openSearchRangeName()
      this._openSearchProductName()
    },
    // 仪器名称
    _openSearchEquipName(name = '') {
      // const data = {
      //   item: 'name',
      //   name: name
      // }
      // this.$store.dispatch('LmsEquipInfo/equipNameList', data).then(() => {
      //   const nameList = this.$store.state.LmsEquipInfo.list
      //   this.nameList = nameList
      // })
    },
    // _nameChange(msg, data) {
    //   switch (msg) {
    //     case 'select':
    //       this.formObj.name = data;
    //       break;
    //     default:
    //       this.formObj.name = data;
    //       this._openSearchEquipName(data);
    //       break;
    //   }
    // },
    // 仪器规格型号
    _openSearchSpecName(spec = '') {
      // const data = {
      //   item: 'spec',
      //   name: spec
      // }
      // this.$store.dispatch('LmsEquipInfo/specNameList', data).then(() => {
      //   const specList = this.$store.state.LmsEquipInfo.list
      //   this.specList = specList
      // })
    },
    // _specChange(msg, data) {
    //   switch (msg) {
    //     case 'select':
    //       this.formObj.spec = data;
    //       break;
    //     default:
    //       this.formObj.spec = data;
    //       this._openSearchSpecName(data);
    //       break;
    //   }
    // },
    // 制造厂商
    _openSearchProductName(product = '') {
      // const data = {
      //   item: 'product_place',
      //   name: product
      // }
      // this.$store.dispatch('LmsEquipInfo/productNameList', data).then(() => {
      //   const productList = this.$store.state.LmsEquipInfo.list
      //   this.productPlaceList = productList
      // })
    },
    // _productPlaceChange(msg, data) {
    //   switch (msg) {
    //     case 'select':
    //       this.formObj.productPlace = data;
    //       break;
    //     default:
    //       this.formObj.productPlace = data;
    //       this._openSearchProductName(data);
    //       break;
    //   }
    // },
    // 用途
    _openSearchRangeName(purpose = '') {
      // const data = {
      //   item: 'purpose',
      //   name: purpose
      // }
      // this.$store.dispatch('LmsEquipInfo/rangeNameList', data).then(() => {
      //   const rangeList = this.$store.state.LmsEquipInfo.list
      //   this.rangeList = rangeList
      // })
    },
    // _rangeChange(msg, data) {
    //   switch (msg) {
    //     case 'select':
    //       this.formObj.range = data;
    //       break;
    //     default:
    //       this.formObj.range = data;
    //       this._openSearchRangeName(data);
    //       break;
    //   }
    // },
    _selectRowChange(data) {
      const idList = []
      for (let i = 0; i < data.length; i++) {
        idList.push(data[i].id)
      }
      this.selectIds = idList
    },
    _selectAll: function(data) {
      this._selectRowChange(data)
    },
    _deleteByIds(ids, content) {
      this.$Modal.confirm({
        title: '提示',
        content: content || '确定删除该记录？',
        onOk: () => {
          // this.$store
          //   .dispatch('LmsEquipPurchaseDetail/deleteByIds', ids)
          //   .then(() => {
          //     if (this.$store.state.LmsEquipPurchaseDetail.success) {
          //       this._purchaseData()
          //       this.$Message.success('删除成功！')
          //     }
          //   })
        }
      })
    },
    _deleteById(id) {
      // 删除一条记录
      this.$Modal.confirm({
        title: '提示',
        content: '确定删除该记录？',
        onOk: () => {
          // this.$store
          //   .dispatch('LmsEquipPurchaseDetail/deleteByIds', id)
          //   .then(() => {
          //     if (this.$store.state.LmsEquipPurchaseDetail.success) {
          //       this._purchaseData()
          //       this.$Message.success('删除成功！')
          //     }
          //   })
        }
      })
    },
    _deleteSelected() {
      // 批量删除
      const ids = this.selectIds
      if (ids === '') {
        this.$Message.warning('请选择一条或多条数据！')
      } else {
        this._deleteByIds(ids, '确定删除 ' + ids.length + ' 条记录？')
      }
    },
    _editModal() {
      // 添加
      this.$refs.editModal._open(this.dataObj.purchaseId)
    },
    _resultChange(msg) {
      this.showEditModal = false
      this.$Message.success(msg)
      this.$emit('on-result-change')
    },
    _ok(status) {
      this.status = status
      this.$refs.formObj.validate(valid => {
        if (valid) {
          if (
            status === 1 &&
            (this.getPage.records === '' || this.getPage.records === undefined)
          ) {
            this.$Message.warning('请添加仪器后再提交！')
            return
          }
          if (this.status === 1) {
            this._dicSearch()
          } else {
            this._save()
          }
        } else {
          this.$Message.error('表单验证失败!')
        }
      })
    },
    _userData(data) {
      this.sendUserId = data.userId
      this._save()
      console.log('this.sendUserId========', data)
    },
    _dicSearch: async function() {
      const result = await dict.getItem('仪器采购申请是否需要提交审批人')
      if (result) {
        const approvalList = result
        if (approvalList.length !== 0) {
          this.isApproval = approvalList[0].name
          if (this.isApproval === '是') {
            this.$refs.selectUser._open()
          } else {
            this._save()
          }
        } else {
          this._save()
        }
      }
    },
    _save() {
      const data = this.$serialize('edit-form')
      this.$extend(data, { status: this.status })
      if (this.sendUserId) {
        data.sendUserId = this.sendUserId
      }
      if (this.$string(this.id).isEmpty()) {
        // 添加
        // this.$store.dispatch('LmsEquipPurchase/add', data).then(() => {
        //   this._resultChange('添加成功!')
        // })
        this._add(data)
      } else {
        // 编辑
        // this.$store
        //   .dispatch('LmsEquipPurchase/edit', { id: this.formObj.id, obj: data })
        //   .then(() => {
        //     this._resultChange('编辑成功!')
        //   })
        data.id = this.formObj.id
        this._edit({ id: this.formObj.id, obj: data })
      }
    },

    _add: async function(data) {
      const result = await equipPurchase.add(data)
      if (result) {
        this._resultChange('添加成功')
      }
    },

    _edit: async function(data) {
      const result = await equipPurchase.edit(data)
      if (result) {
        this._resultChange('编辑成功')
      }
    },

    _cancel() {
      this.showEditModal = false
    },
    _purchaseData: async function(purchaseId) {
      alert(this.purchaseId)
      alert(purchaseId)
      const result = await equipPurchaseDetail.list(this.dataObj)
      if (result) {
        this.getPage.records = result
      }
      // this.$store
      //   .dispatch('LmsEquipPurchaseDetail/list', this.dataObj)
      //   .then(() => {
      //     this.getPage.records = this.$store.state.LmsEquipPurchaseDetail.list
      //   })
    }
  }
}
</script>
<style>
.ivu-select-dropdown-list {
  max-height: 200px;
}
</style>
