<template>
  <div>
    <!-- 执行顺序 -->
    <Alert class="equip_alert">
      <div>
        <table class="tableClass">
          <tbody>
            <tr>
              <th colspan="6" style="text-align: center;font-size: 15px">
                耗材采购申请单
              </th>
            </tr>
            <tr>
              <th>编号</th>
              <td>{{ getOrder.num }}</td>
              <th>申请人</th>
              <td>{{ getOrder.applyer }}</td>
              <th>申请时间</th>
              <td>{{ getOrder.ctime?$dateformat(getOrder.ctime, 'yyyy-mm-dd HH:MM'):'' }}</td>
            </tr>
            <tr>
              <th>申请原因</th>
              <td colspan="5">
                {{ getOrder.remark }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <Form inline :label-width="100">
        <Form-item label="一级审批意见:" prop="firstStepAdvice" style="width:70%;margin-top: 20px">
          <el-input v-model="getOrder.postil" readonly/>
        </Form-item>
        <FormItem label="审批意见：" style="width:70%;">
          <el-input v-model="secondPostil" placeholder="请输入审批意见..." :rows="2" type="textarea"/>
        </FormItem>
        <div align="left" style="margin-top: 12px;display: inline-block;" class="btn-width">
          <el-button type="success" @click="_approve(3,'确定通过？')">
            同意
          </el-button>
          <el-button type="danger" @click="_approve(5,'确定驳回？')">
            驳回
          </el-button>
          <el-button type="danger" @click="_approve(2,'确定终止？')">
            终止
          </el-button>
        </div>
      </Form>
    </Alert>
    <!--内容-->
    <div>
      <element-table
        ref="pageTable"
        :table-height="450"
        :get-page="getPage"
        editable
        @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?item.width:200"
          :fixed="item.fixed?item.fixed:undefined"
        >
          <template slot-scope="scope">
            <div v-if="item.key==='quantity'">
              <div v-if="scope.row.editable">
                <el-input
                  v-model="scope.row.quantity"
                  placeholder="请输入采购数量"
                  size="small"
                  @focus="_handleRow(scope)"
                  @blur="_save(item.key)"
                />
              </div>
              <div v-else>
                {{ scope.row.quantity }}
              </div>
            </div>
            <div v-else-if="item.key==='price'">
              <div v-if="scope.row.editable">
                <el-input
                  v-model="scope.row.price"
                  placeholder="请输入单价"
                  size="small"
                  @focus="_handleRow(scope)"
                  @blur="_save(item.key)"
                />
              </div>
              <div v-else>
                {{ scope.row.price }}
              </div>
            </div>
            <div v-else-if="item.key==='spec'">
              <div v-if="scope.row.editable">
                <autoCompletes
                  :value="scope.row.spec"
                  placeholder="请输入或选择规格"
                  :down-data="specList"
                  :handle-obj="scope"
                  blur
                  focus
                  @on-result-change="_specChange"
                />
              </div>
              <div v-else>
                {{ scope.row.spec }}
              </div>
            </div>
            <div v-else-if="item.key==='quality'">
              <div v-if="scope.row.editable">
                <autoCompletes
                  :value="scope.row.quality"
                  placeholder="请输入或选择等级"
                  :down-data="qualityList"
                  :handle-obj="scope"
                  blur
                  focus
                  @on-result-change="_qualityChange"
                />
              </div>
              <div v-else>
                {{ scope.row.quality }}
              </div>
            </div>
            <div v-else-if="item.key==='manufacturer'">
              <div v-if="scope.row.editable">
                <autoCompletes
                  :value="scope.row.manufacturer"
                  placeholder="请输入或选择制造厂商"
                  :down-data="manufacturerList"
                  :handle-obj="scope"
                  blur
                  focus
                  @on-result-change="_manufacturerChange"
                />
              </div>
              <div v-else>
                {{ scope.row.manufacturer }}
              </div>
            </div>
            <div v-else-if="item.key==='supplier'">
              <div v-if="scope.row.editable">
                <autoCompletes
                  :value="scope.row.supplier"
                  placeholder="请输入或选择制造厂商"
                  :down-data="supplierList"
                  :handle-obj="scope"
                  blur
                  focus
                  @on-result-change="_supplierChange"
                />
              </div>
              <div v-else>
                {{ scope.row.supplier }}
              </div>
            </div>
            <div v-else-if="item.key==='remark'">
              <div v-if="scope.row.editable">
                <el-input
                  v-model="scope.row.remark"
                  placeholder="请输入备注"
                  size="small"
                  @focus="_handleRow(scope)"
                  @blur="_save(item.key)"
                />
              </div>
              <div v-else>
                {{ scope.row.remark }}
              </div>
            </div>
            <div v-else>
              {{ scope.row[item.key] }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          slot="col"
          label="操作"
          align="center"
          :width="100"
          fixed="right"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.state===1">
              已拒绝
            </div>
            <icon-list v-else :msg="iconMsg" :row-data="scope.row" @on-result-change="_iconClick" />
          </template>
        </el-table-column>
      </element-table>
    </div>
    <!--编辑-->
    <el-dialog
     v-dialogDrag
     :visible.sync="showModal"
     :close-on-click-modal="false"
     width="700px"
     title="拒绝">
      <div>
        <Form ref="formObj" :model="formObj" :rules="ruleValidate" :label-width="50">
          <Form-item label="备注" prop="remark">
            <Input v-model="formObj.remark" name="remark" placeholder="请输入备注" />
          </Form-item>
        </Form>
      </div>
      <div slot="footer" class="btn-width">
        <el-button @click="_cancel">
          取消
        </el-button>
        <el-button type="primary" @click="_refuse">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import global from '../../../api/config'
import {
  chemicalRelPurchase,
  chemicalPurchaseOrder,
  chemical,
  supplier
} from '../../../api'
import autoCompletes from '../../../components/base/autoCompletes'
/**
 * 二级审批：---- 是不是走第二步审批，后端根据配置的字典（耗材采购是否需要二级审批）来判断
 */
export default {
  components: {
    autoCompletes
  },
  data() {
    return {
      getOrder: {},
      getPage: {},
      currentRow: {},
      pageColumns: [
        { title: '耗材编号', key: 'chemicalNum', width: 160 },
        { title: '耗材名称', key: 'chemicalName', width: 160 },
        { title: '单价', key: 'price', width: 100 },
        { title: '采购数量', key: 'quantity', width: 100 },
        { title: '计量单位', key: 'unit', width: 100 },
        { title: '规格', key: 'spec', width: 100 },
        { title: '等级（纯度）', key: 'quality', width: 140 },
        { title: '供应商', key: 'supplier', width: 200 },
        { title: '制造厂商', key: 'manufacturer', width: 200 },
        { title: '备注', key: 'remark' }
      ],
      iconMsg: [{ type: 'pt-back', id: '', name: '拒绝' }],
      id: {},
      step: '',
      showModal: false,
      formObj: {
        id: '',
        remark: ''
      },
      ruleValidate: {
        remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }]
      },
      // 规格
      specList: [],
      specListTemp: [],
      // 等级
      qualityList: [],
      qualityListTemp: [],
      // 制造厂商
      manufacturerList: [],
      manufacturerListTemp: [],

      supplierList: [],
      secondPostil: '同意'
    }
  },
  mounted() {
    this.id = this.$route.query.id
    this.step = this.$route.query.step
    this._page()
    this._purchaseOrder(this.id)
    const list = [
      { key: 'spec', value: 'specList' },
      { key: 'quality', value: 'qualityList' },
      { key: 'manufacturer', value: 'manufacturerList' }
    ]

    for (let i = 0; i < list.length; i++) {
      this._dicSearch(list[i])
    }
  },
  methods: {
    _handleRow(data) {
      this.currentRow = data.row
    },
    _page: async function() {
      const obj = Object.assign(
        { orderId: this.id },
        this.$refs.pageTable._searchParams()
      )
      const result = await chemicalRelPurchase.purchaseChemicalPage(
        this.$serializeForm(obj)
      )
      if (result) {
        this.getPage = result
        this.$refs.pageTable._initTable()
      }
    },
    _tableResultChange(msg, data) {
      switch (msg) {
        case 'page':
          this._page()
          break
      }
    },
    _purchaseOrder: async function(id) {
      this.getOrder = await chemicalPurchaseOrder.getById(id)
    },
    _approve(allow, content) {
      this.$confirm(content, '提示', { type: 'warning' }).then(() => {
        const data = {}
        data.id = $('#flowFrame', parent.document).attr('data-tid')
        data.allow = allow
        data.step = this.step
        data.postil = this.secondPostil
        this._approveOk(data)
      })
    },
    _approveOk: async function(data) {
      const result = await chemicalPurchaseOrder.approveManager(data)
      if (result) {
        this.$message.success('审批成功！')
        setTimeout(() => {
          parent.location.replace(global.webURL + '/sys/workflow/flow_task')
        }, 200)
      }
    },

    _iconClick(res, data) {
      switch (res) {
        case '拒绝':
          this.showModal = true
          this.formObj.remark = ''
          this.formObj.id = data.id
          break
      }
    },
    _cancel() {
      this.showModal = false
    },
    _dicSearch: async function(data) {
      const result = await chemical.getItems(data.key)
      if (result) {
        this[data.value] = []
        this[data.value + 'Temp'] = []
        for (let i = 0; i < result.length; i++) {
          const obj = result[i]
          this[data.value].push(obj[data.key])
          this[data.value + 'Temp'].push(obj[data.key])
        }
      }
    },
    _save: async function(key) {
      const obj = {
        id: this.currentRow.id,
        obj: { [key]: this.currentRow[key] }
      }
      const result = await chemicalRelPurchase.editChemical(obj)
      if (result) {
        // this._page()
      }
    },
    _refuse() {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          this._refuseOk()
        } else {
          this.$message.error('表单验证失败!')
        }
      })
    },
    _refuseOk: async function() {
      const result = await chemicalRelPurchase.rejectPurchase(this.formObj)
      if (result) {
        this.showModal = false
        this.$message.success('操作成功')
        this._page()
      }
    },
    _specChange(msg, data, handleObj) {
      this._handleRow(handleObj)
      switch (msg) {
        case 'select':
          this.currentRow.spec = data
          this._save('spec')
          break
        case 'blur':
          this._save('spec')
          break
        case 'focus':
          this.specList = JSON.parse(JSON.stringify(this.specListTemp))
          break
        case 'query':
          this.specList = this.specListTemp.filter(
            item => item.indexOf(data) > -1
          )
          break
      }
    },
    _qualityChange(msg, data, handleObj) {
      this._handleRow(handleObj)
      switch (msg) {
        case 'select':
          this.currentRow.quality = data
          this._save('quality')
          break
        case 'blur':
          this._save('quality')
          break
        case 'focus':
          this.qualityList = JSON.parse(JSON.stringify(this.qualityListTemp))
          break
        case 'query':
          this.qualityList = this.qualityListTemp.filter(
            item => item.indexOf(data) > -1
          )
          break
      }
    },
    _manufacturerChange(msg, data, handleObj) {
      this._handleRow(handleObj)
      switch (msg) {
        case 'select':
          this.currentRow.manufacturer = data
          this._save('manufacturer')
          break
        case 'blur':
          this._save('manufacturer')
          break
        case 'focus':
          this.manufacturerList = JSON.parse(
            JSON.stringify(this.manufacturerListTemp)
          )
          break
        case 'query':
          this.manufacturerList = this.manufacturerListTemp.filter(
            item => item.indexOf(data) > -1
          )
      }
    },
    _supplierChange(msg, data, handleObj) {
      this._handleRow(handleObj)
      switch (msg) {
        case 'select':
          this.currentRow.supplier = data
          this._save('supplier')
          break
        case 'blur':
          this._save('supplier')
          break
        case 'focus':
          this._supplierQuery()
          break
        case 'query':
          this._supplierQuery(data)
      }
    },
    _supplierQuery: async function(name) {
      const data = {}
      if (name) {
        data.name = name
      }
      const result = await supplier.page(data)
      this.supplierList = []
      for (let i = 0; i < result.records.length; i++) {
        this.supplierList.push(result.records[i].name)
      }
    }
  }
}
</script>
