<template>
  <el-form
    ref="dataForm"
    class="form"
    v-loading="loading"
    :model="dataForm"
    :rules="dataFormRules"
    label-position="left"
    label-width="130px"
  >
    <el-form-item v-if="formDisabled" label="单据编号" prop="purchaseAdjustmentId">
      <el-input disabled :value="dataForm.purchaseAdjustmentId" />
    </el-form-item>
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12">
        <el-form-item
          label="网点"
          prop="websitId"
          :rules="[{ required: true, message: '请选择网点', trigger: 'change' }]"
        >
          <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 :xs="24" :sm="12">
        <el-form-item
          label="采购单号"
          prop="ref"
          :rules="[
            { required: true, message: '请输入采购单号', trigger: 'blur' },
            {
              min: 16,
              max: 32,
              message: '请输入正确采购单号',
              trigger: 'change'
            }
          ]"
        >
          <el-input
            v-model="dataForm.ref"
            :disabled="formDisabled"
            autocomplete="off"
            placeholder="采购单号"
            @keyup.enter.native.prevent="getAndSaveSheet"
          >
            <el-button
              v-if="dataForm.purchaseAdjustmentId === ''"
              slot="append"
              icon="el-icon-search"
              @click.prevent="getAndSaveSheet"
            />
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col v-if="formDisabled" :xs="24" :sm="12">
        <el-form-item label="采购日期" prop="purchaseTime">
          <el-date-picker
            v-model="dataForm.purchaseTime"
            type="date"
            placeholder="选择日期"
            :disabled="formDisabled"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col v-if="formDisabled" :xs="24" :sm="12">
        <el-form-item label="单据状态" prop="flag">
          <el-select v-model="dataForm.flag" disabled placeholder="单据状态" style="width: 100%">
            <el-option
              v-for="(item, index) in sheetFlagStr('select')"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item label="备注" prop="notes">
      <el-input
        v-model="dataForm.notes"
        autocomplete="off"
        placeholder="备注"
        :disabled="dataForm.flag !== 0 || inputParam.openType === 'view'"
      />
    </el-form-item>
    <el-row v-show="dataForm.purchaseAdjustmentId !== ''">
      <el-col :span="24">
        <el-divider>采购明细</el-divider>
      </el-col>
      <el-col :span="24">
        <el-table
          ref="goodsTable"
          :data="dataForm.items"
          max-height="500"
          size="mini"
          border
          header-cell-class-name="headerRowColor"
          style="width: 100%"
        >
          <el-table-column prop="goodsId" label="辅材编号" min-width="160" />
          <el-table-column prop="goodsName" label="辅材名称" min-width="160" />
          <el-table-column prop="cost" label="采购进价" header-align="left" align="center" min-width="160" />
          <el-table-column prop="recQty" label="采购数量" header-align="left" align="center" min-width="160" />
          <el-table-column prop="recGiftQty" label="采购赠品数量" header-align="left" align="center" min-width="160" />
          <el-table-column prop="inStockQty" label="采购入库数量" header-align="left" align="center" min-width="160" />
          <el-table-column prop="inStockCost" label="采购入库进价" header-align="left" align="center" min-width="160" />
          <el-table-column prop="adjustCost" label="调整进价" header-align="left" align="center" min-width="160">
            <template slot-scope="{ $index, row }">
              <label v-if="inputParam.openType === 'view' || dataForm.flag !== 'SAVE'">{{ row.adjustCost }}</label>
              <el-form-item
                v-else
                style="margin: 18px 0"
                label-width="0"
                size="mini"
                :prop="'items.' + $index + '.adjustCost'"
                :rules="dataFormRules.adjustCost"
              >
                <el-input v-model="row.adjustCost" size="mini" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="adjustQty" label="调整数量" header-align="left" align="center" min-width="160">
            <template slot-scope="{ $index, row }">
              <label v-if="inputParam.openType === 'view' || dataForm.flag !== 'SAVE'">{{ row.adjustQty }}</label>
              <el-form-item
                v-else
                style="margin: 18px 0"
                label-width="0"
                size="mini"
                :prop="'items.' + $index + '.adjustQty'"
                :rules="dataFormRules.adjustQty"
              >
                <el-input v-model="row.adjustQty" size="mini" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="adjustGiftQty" label="调整赠品数量" header-align="left" align="center" min-width="160">
            <template slot-scope="{ $index, row }">
              <label v-if="inputParam.openType === 'view' || dataForm.flag !== 'SAVE'">{{ row.adjustGiftQty }}</label>
              <el-form-item
                v-else
                style="margin: 18px 0"
                label-width="0"
                size="mini"
                :prop="'items.' + $index + '.adjustGiftQty'"
                :rules="dataFormRules.adjustGiftQty"
              >
                <el-input v-model="row.adjustGiftQty" size="mini" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            prop="adjustInStockQty"
            label="调整入库数量"
            header-align="left"
            align="center"
            min-width="160"
          />
          <el-table-column
            prop="adjustInStockCost"
            label="调整入库进价"
            header-align="left"
            align="center"
            min-width="160"
          />
          <el-table-column prop="measureUnit" label="采购单位" min-width="160" />
          <el-table-column prop="unitQty" label="转换系数" header-align="left" align="center" min-width="160" />
          <el-table-column prop="salesUnit" label="售卖单位" min-width="160" />
          <el-table-column prop="productModel" label="商品型号" min-width="160" />
          <el-table-column prop="specification" label="规格" min-width="160" />
        </el-table>
        <el-row>
          <el-col :span="24"
            ><div style="padding-top: 15px">共 {{ dataForm.items.length }} 条记录</div></el-col
          >
        </el-row>
      </el-col>
    </el-row>
    <div style="text-align: right">
      <el-button @click="cancelForm">取 消</el-button>
      <el-button
        v-if="$restrict('edit') && dataForm.flag === 'SAVE'"
        type="primary"
        :disabled="saveBtn"
        @click="submitForm('edit')"
        >保 存</el-button
      >
      <el-button v-if="$restrict('submit') && dataForm.flag === 'SAVE'" type="success" @click="submitForm('submit')"
        >提 交</el-button
      >
      <el-button v-if="$restrict('confirm') && dataForm.flag === 'SUBMIT'" type="success" @click="submitForm('confirm')"
        >审 核</el-button
      >
      <el-button v-if="$restrict('revoke') && dataForm.flag === 'SUBMIT'" type="danger" @click="submitForm('revoke')"
        >撤 消</el-button
      >
    </div>
  </el-form>
</template>

<script>
import {
  purchaseAdjustmentSheetDetail,
  purchaseAdjustmentSheetAdd,
  purchaseAdjustmentSheetEdit,
  purchaseAdjustmentSheetSubmit,
  purchaseAdjustmentSheetRevoke,
  purchaseAdjustmentSheetConfirm
} from '@/api/material-system/shop/purchase-adjustment-sheet'
import { getWebsit } from '@/api/customerManagement.js'
export default {
  name: 'PurchaseAdjustmentArea',
  props: {
    inputParam: {
      type: Object,
      default: function () {
        return {
          openType: 'add',
          purchaseAdjustmentId: ''
        }
      }
    }
  },
  data() {
    const validateCost = (rule, value, callback) => {
      this.saveBtn = true
      if (!value) {
        return callback(new Error('不能为空'))
      }
      if (Number.isNaN(parseFloat(value))) {
        return callback(new Error('请输入数字值'))
      }
      if (parseFloat(value) <= 0) {
        return callback(new Error('必须大于0'))
      }
      this.saveBtn = false
      callback()
    }
    const validateQty = (rule, value, callback) => {
      this.saveBtn = true
      if (!value) {
        return callback(new Error('不能为空'))
      }
      if (Number.isNaN(parseFloat(value))) {
        return callback(new Error('请输入数字值'))
      }
      if (parseFloat(value) <= 0) {
        return callback(new Error('必须大于0'))
      }
      this.saveBtn = false
      callback()
    }
    const validateGiftQty = (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: true,
      dataForm: {
        purchaseAdjustmentId: '',
        websitId: '', // 网点编号
        websitName: '', // 网点名称
        ref: '', // 采购单号
        purchaseTime: '', // 采购日期
        flag: '', // 状态
        notes: '', // 备注
        items: []
      },
      dataFormRules: {
        adjustCost: [{ validator: validateCost, trigger: 'blur' }],
        adjustQty: [{ validator: validateQty, trigger: 'blur' }],
        adjustGiftQty: [{ validator: validateGiftQty, trigger: 'blur' }]
      },
      saveBtn: false, // 保存按钮状态
      authShop: []
    }
  },
  computed: {
    formDisabled() {
      return this.dataForm.purchaseAdjustmentId !== ''
    }
  },
  mounted() {
    this.getDetail()
    getWebsit({ type: 'C', status: true }).then(res => {
      this.authShop = res.data
    })
  },
  methods: {
    sheetFlagStr(type, val, filterArrays) {
      const flag = [
        { label: '保存', value: 'SAVE' },
        { label: '提交', value: 'SUBMIT' },
        { label: '作废', value: 'FAIL' },
        { label: '已审核', value: 'OK' }
      ].filter(obj => {
        if (filterArrays) {
          return filterArrays.indexOf(obj.value) >= 0
        }
        return true
      })
      if (type === 'select') {
        // 下拉选择返回数组
        return flag
      } else if (type === 'label') {
        // 显示代号返回字符
        if (val === null || val === '') return ''
        const obj = flag.find(o => o.value === val)
        return obj ? obj.label : ''
      }
      return ''
    },
    // 获取详情
    getDetail(id) {
      this.loading = true
      const openType = this.inputParam.openType
      const purchaseAdjustmentId = id || this.inputParam.purchaseAdjustmentId
      if (openType !== 'add') {
        purchaseAdjustmentSheetDetail({ purchaseAdjustmentId }).then(res => {
          this.setDataForm(res.data)
          this.loading = false
        })
      } else {
        this.loading = false
      }
    },
    getAndSaveSheet() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.dataForm.purchaseAdjustmentId === '') {
            const params = {
              websitId: this.dataForm.websitId,
              websitName: this.authShop.find(item => item.websitId === this.dataForm.websitId)?.name,
              ref: this.dataForm.ref,
              notes: this.dataForm.notes
            }
            purchaseAdjustmentSheetAdd(params).then(res => {
              this.cancelForm()
            })
          }
        }
      })
    },
    setDataForm(data) {
      this.dataForm = {
        purchaseAdjustmentId: data.purchaseAdjustmentId,
        websitId: data.websitId,
        websitName: data.websitName,
        ref: data.ref,
        purchaseTime: data.purchaseTime,
        flag: data.flag,
        notes: data.notes,
        items: data.items,
        isRecheck: data.isRecheck
      }
    },
    submitForm(type) {
      if (type === 'edit') {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            purchaseAdjustmentSheetEdit(this.dataForm).then(() => {
              this.$successMsg('保存成功')
              this.getDetail(this.dataForm.purchaseAdjustmentId)
            })
          }
        })
      } else {
        this[type + 'Sheet'](this.dataForm.purchaseAdjustmentId)
      }
    },
    cancelForm() {
      this.$parent.backUpdPage()
    },
    // 提交采购调整单
    submitSheet(purchaseAdjustmentId) {
      this.$confirm(`此操作将提交 ${purchaseAdjustmentId} 单据, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.listLoading = true
          purchaseAdjustmentSheetSubmit({ purchaseAdjustmentId: purchaseAdjustmentId }).then(
            () => {
              this.inputParam.openType = 'view'
              this.getDetail(purchaseAdjustmentId)
              this.$successMsg('提交成功')
            },
            () => {
              this.loading = false
            }
          )
        })
        .catch(() => console.log('取消'))
    },
    // 撤消采购调整单
    revokeSheet(purchaseAdjustmentId) {
      this.$confirm(`此操作将撤消 ${purchaseAdjustmentId} 单据, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.listLoading = true
          purchaseAdjustmentSheetRevoke({ purchaseAdjustmentId: purchaseAdjustmentId }).then(
            () => {
              this.inputParam.openType = 'edit'
              this.getDetail(purchaseAdjustmentId)
              this.$successMsg('撤消成功')
            },
            () => {
              this.loading = false
            }
          )
        })
        .catch(() => console.log('取消'))
    },
    // 审核采购调整单
    confirmSheet(purchaseAdjustmentId) {
      this.$confirm(`此操作将审核 ${purchaseAdjustmentId} 单据, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.listLoading = true
          purchaseAdjustmentSheetConfirm({ purchaseAdjustmentId: purchaseAdjustmentId }).then(
            () => {
              this.getDetail(purchaseAdjustmentId)
              this.$successMsg('审核成功')
            },
            () => {
              this.loading = false
            }
          )
        })
        .catch(() => console.log('取消'))
    }
  }
}
</script>

<style scoped>
.form {
  padding: 0 20px;
}
</style>
