<template>
  <el-form
    ref="dataForm"
    v-loading="loading"
    :model="dataForm"
    :rules="dataFormRules"
    label-position="left"
    label-width="90px"
  >
    <el-form-item v-if="formDisabled" label="单据编号" prop="purchaseId">
      <el-input disabled :value="dataForm.purchaseId" />
    </el-form-item>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="网点" prop="websitId">
          <el-select v-model="dataForm.websitId" :disabled="formDisabled" placeholder="请选择网点" style="width: 100%">
            <el-option v-for="(item, index) in authShop" :key="index" :label="item.name" :value="item.websitId" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="供应商" prop="venderId">
          <el-select
            v-model="dataForm.venderId"
            filterable
            :disabled="formDisabled"
            placeholder="请选择供应商"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in venderList"
              :key="index"
              :label="item.venderName"
              :value="item.venderId"
              :disabled="item.status !== 'ON'"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="状态" prop="flag">
          <!-- <el-input disabled :value="sheetFlagStr('label', dataForm.flag)" /> -->
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item v-if="dataForm.notes3" label="申请单备注">
      <el-input v-model="dataForm.notes3" disabled />
    </el-form-item>
    <el-form-item label="备注">
      <el-input
        v-model="dataForm.notes2"
        autocomplete="off"
        placeholder="备注"
        :disabled="inputParam.openType === 'view'"
      />
    </el-form-item>
    <el-row>
      <el-col>
        <el-divider>采购明细</el-divider>
      </el-col>
      <el-col>
        <el-table
          ref="goodsTable"
          :data="dataForm.items"
          max-height="500"
          size="mini"
          border
          header-cell-class-name="headerRowColor"
          class="detail-table"
          show-summary
          :summary-method="getSummaries"
        >
          <el-table-column prop="goodsId" label="辅材编号" />
          <el-table-column prop="goodsName" label="辅材名称" width="230" />
          <el-table-column prop="estimateCost" label="预估进价" header-align="left" align="center" />
          <el-table-column prop="purchaseQty" label="订货数量" header-align="left" align="center" />
          <el-table-column prop="deliverQty" label="供应数量" header-align="left" align="center">
            <template slot-scope="{ $index, row }">
              <label v-if="inputParam.openType === 'view'">{{ row.deliverQty + ' /' + row.measureUnit }}</label>
              <el-form-item
                v-else
                style="margin: 18px 0"
                label-width="0"
                size="mini"
                :prop="'items.' + $index + '.deliverQty'"
                :rules="dataFormRules.deliverQty"
              >
                <el-input v-model="row.deliverQty" size="mini">
                  <template slot="suffix">{{ ' /' + row.measureUnit }}</template>
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <template v-if="dataForm.flag === 100">
            <el-table-column prop="recQty" label="验收数量" />
            <el-table-column prop="recGiftQty" label="验收赠品数量" />
          </template>
          <el-table-column prop="measureUnit" label="采购单位" />
          <el-table-column prop="productModel" label="商品型号" />
          <el-table-column prop="specification" label="规格" />
        </el-table>
        <el-row>
          <el-col :span="24"
            ><div>共 {{ goodsTotalCount }} 条记录</div></el-col
          >
        </el-row>
      </el-col>
    </el-row>
    <div style="text-align: right">
      <el-button @click="cancelForm">取 消</el-button>
      <el-button v-if="checkBtn('edit')" type="primary" :disabled="saveBtn" @click="submitForm('edit')"
        >保 存</el-button
      >
      <el-button v-if="checkBtn('verify')" type="success" @click="verifySheet(dataForm.purchaseId)">核 实</el-button>
      <el-button v-if="checkBtn('revoke')" type="danger" @click="revokeSheet(dataForm.purchaseId)">撤 消</el-button>
    </div>
  </el-form>
</template>

<script>
import {
  editPurchaseApplySheet,
  revokePurchaseApplySheet,
  getPurchaseApplySheet,
  verifyPurchaseApplySheet
} from '@/api/material-system/vender/shop-purchase-apply'
import { getVenderList } from '@/api/material-system/vender'
import { listPageV2 } from '@/api/auxiliaryFittings/supplier'
import { getWebsit } from '@/api/customerManagement.js'
export default {
  name: 'ShopPurchaseArea',
  props: {
    inputParam: {
      type: Object,
      default: function () {
        return {
          openType: 'add',
          purchaseId: ''
        }
      }
    }
  },
  data() {
    const validateDeliverQty = (rule, value, callback) => {
      this.saveBtn = true
      if (Number.isNaN(parseFloat(value))) {
        return callback(new Error('请输入数字值'))
      }
      if (parseFloat(value) < 0) {
        return callback(new Error('不能少于0'))
      }
      this.saveBtn = false
      callback()
    }
    return {
      loading: false,
      dataForm: {
        purchaseId: '', // 单据ID
        websitId: '', // 网点ID
        websitName: '', // 网点名称
        venderId: '', // 供应商ID
        venderName: '', // 供应商名称
        notes2: '', // 备注
        notes3: '', // 网点备注
        flag: '',
        items: [] // 关系辅材列表
      },
      dataFormRules: {
        deliverQty: [{ validator: validateDeliverQty, trigger: 'blur' }]
      },
      venderList: [],
      saveBtn: false // 保存按钮状态
    }
  },
  computed: {
    formDisabled() {
      return this.inputParam.openType === 'view' || this.dataForm.purchaseId !== ''
    },
    goodsTotalCount: function () {
      return this.dataForm && this.dataForm.items ? this.dataForm.items.length : 0
    }
  },
  mounted() {
    this.getVenderList()
    this.getDetail()
    getWebsit({ type: 'C', status: true }).then(res => {
      this.authShop = res.data
    })
  },
  methods: {
    // 获取供应商列表
    getVenderList() {
      listPageV2({
        pageNum: 1,
        pageSize: -1,
        params: [
          { param: 'a.status', compare: '=', value: 'ON' },
          { param: 'a.vender_type', compare: 'like', value: '辅材' }
        ]
      }).then(res => {
        this.venderList = res.data.records
      })
    },
    getDetail(id) {
      if (id || this.inputParam.purchaseId) {
        this.loading = true
        getPurchaseApplySheet({ purchaseId: id || this.inputParam.purchaseId }).then(res => {
          this.loading = false
          this.setDataForm(res.data)
        })
      }
    },
    cancelForm() {
      this.$parent.$refs.pageRef.refreshList()
      this.$emit('update:isOpen', false)
    },
    submitForm(type) {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          editPurchaseApplySheet(this.dataForm).then(() => {
            this.$successMsg('保存成功')
          })
        }
      })
    },
    setDataForm(data) {
      this.dataForm = {
        purchaseId: data.purchaseId, // 单据编号
        websitId: data.websitId, // 网点ID
        venderId: data.venderId, // 供应商Id
        flag: data.flag,
        notes: data.notes, // 备注
        items: data.items // 关系商品列表
      }
    },
    checkBtn(type) {
      const typeMap = {
        add: this.inputParam.openType === type,
        edit: this.dataForm.flag === 1 && this.inputParam.openType === type,
        revoke: this.dataForm.flag === 1,
        verify: this.dataForm.flag === 1
      }
      // 检查按钮权限
      return true // this.checkBtnRole(type) && typeMap[type]
    },

    // 核实 采购申请单
    verifySheet(purchaseId) {
      this.$confirm(
        `此操作将核实 ${purchaseId} 单据，<span style="color: #ff0000;">当前内容如果已修改将忽略保存</span>，是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }
      )
        .then(() => {
          this.loading = true
          verifyPurchaseApplySheet({ purchaseId: purchaseId }).then(
            () => {
              setTimeout(() => {
                this.inputParam.openType = 'view'
                this.getDetail(purchaseId)
                this.$successMsg('核实成功')
                this.loading = false
              }, 2000)
            },
            () => {
              this.loading = false
            }
          )
        })
        .catch(() => console.log('取消'))
    },
    // 撤消单据
    revokeSheet(purchaseId) {
      this.$confirm(`此操作将撤消 ${purchaseId} 单据, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          revokePurchaseApplySheet({ purchaseId: purchaseId }).then(() => {
            this.cancelForm()
            this.$successMsg('撤消成功')
          })
        })
        .catch(() => console.log('取消'))
    },

    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
        } else {
          sums[index] = ''
        }
      })

      return sums
    }
  }
}
</script>

<style lang="scss" scoped>
.detail-table {
  width: 100%;
  margin: 15px 0;
  ::v-deep .el-input__suffix-inner {
    color: red;
  }
}
</style>
