<template>
  <el-form
    class="pd"
    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.websitId})${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="purchaseTime">
          <el-date-picker
            v-model="dataForm.purchaseTime"
            type="date"
            placeholder="选择采购日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :disabled="inputParam.openType === 'view'"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="入库仓库" prop="storageId">
          <el-select
            v-model="dataForm.storageId"
            filterable
            :disabled="inputParam.openType === 'view'"
            placeholder="请选择供应商"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in cangkuList"
              :key="index"
              :label="item.storageName"
              :value="item.storageId"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item label="采购单图片" prop="imageUrl">
      <template v-if="inputParam.openType !== 'view'">
        <el-upload
          v-loading="imageLoading"
          element-loading-text="上传中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
          :disabled="imageLoading"
          class="avatar-uploader"
          :action="baseURL + 'common/upload'"
          :headers="myHeaders"
          :show-file-list="false"
          :on-success="uploadSuccess"
          :before-upload="beforeUpload"
          :on-error="uploadError"
        >
          <img v-if="dataForm.imageUrl" :src="$showImgUrl(dataForm.imageUrl)" class="avatar" alt="" />
          <i v-else class="el-icon-plus avatar-uploader-icon" />
          <div slot="tip" class="el-upload__tip" style="margin-top: 0; line-height: 20px">只支持上传jpg/png文件</div>
        </el-upload>
      </template>
      <template v-else>
        <el-image
          v-if="dataForm.imageUrl"
          style="width: 100px; height: 100px"
          :src="$showImgUrl(dataForm.imageUrl)"
          :preview-src-list="[$showImgUrl(dataForm.imageUrl)]"
        />
      </template>
    </el-form-item>
    <el-form-item v-if="dataForm.notes3" label="申请单备注">
      <el-input v-model="dataForm.notes3" disabled />
    </el-form-item>
    <el-form-item v-if="dataForm.notes2" label="供应商备注">
      <el-input v-model="dataForm.notes2" disabled />
    </el-form-item>
    <el-form-item label="备注" prop="notes">
      <el-input
        v-model="dataForm.notes"
        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"
          show-summary
          :summary-method="getSummaries"
          class="detail-table"
        >
          <el-table-column prop="goodsId" label="辅材编号" min-width="140" />
          <el-table-column prop="goodsName" label="辅材名称" min-width="140" />
          <el-table-column prop="applyQty" label="订货数量" header-align="left" align="center" />
          <el-table-column prop="checkQty" label="供应数量" header-align="left" align="center" />
          <el-table-column prop="applyCost" label="预估进价" header-align="left" align="center" />
          <el-table-column prop="cost" label="进价" header-align="left" align="center">
            <template slot-scope="{ $index, row }">
              <label v-if="inputParam.openType === 'view'">{{ row.cost }}</label>
              <el-form-item
                v-else
                style="margin: 18px 0"
                label-width="0"
                size="mini"
                :prop="'items.' + $index + '.cost'"
                :rules="dataFormRules.cost"
              >
                <el-input v-model="row.cost" size="mini" @change="changeCostValue($index, row)" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="recQty" label="验收数量" header-align="left" align="center" width="100">
            <template slot-scope="{ $index, row }">
              <label v-if="inputParam.openType === 'view'">{{ row.recQty + ' /' + row.goodsStockUnit }}</label>
              <el-form-item
                v-else
                style="margin: 18px 0"
                label-width="0"
                size="mini"
                :prop="'items.' + $index + '.recQty'"
                :rules="dataFormRules.recQty"
              >
                <el-input v-model="row.recQty" size="mini" @change="changeCostValue($index, row)">
                  <template slot="suffix">{{ row.goodsStockUnit }}</template>
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="recGiftQty" label="赠品数量" header-align="left" align="center">
            <template slot-scope="{ $index, row }">
              <label v-if="inputParam.openType === 'view'">{{ row.recGiftQty + ' /' + row.goodsStockUnit }}</label>
              <el-form-item
                v-else
                style="margin: 18px 0"
                label-width="0"
                size="mini"
                :prop="'items.' + $index + '.recGiftQty'"
                :rules="dataFormRules.recGiftQty"
              >
                <el-input v-model="row.recGiftQty" size="mini">
                  <template slot="suffix">{{ row.goodsStockUnit }}</template>
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="costValue" label="验收金额" header-align="left" align="center" />
          <el-table-column prop="inStockQty" label="入库数量" header-align="left" align="center" width="100">
            <template slot-scope="{ $index, row }">
              <label>{{ row.inStockQty }}</label>
            </template>
          </el-table-column>
          <el-table-column prop="inStockCost" label="入库进价" header-align="left" align="center" width="100">
            <template slot-scope="{ $index, row }">
              <label>{{ row.inStockCost + ' 元' }}</label>
            </template>
          </el-table-column>
          <el-table-column prop="goodsStockUnit" label="采购单位" />
          <el-table-column prop="goodsSpecification" 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="$restrict('edit') && dataForm.flag === 'SUBMIT' && dataForm.isRecheck === 'YES'"
        type="primary"
        :disabled="saveBtn"
        @click="submitForm('edit')"
        >保 存</el-button
      >
      <el-button
        v-if="$restrict('confirm') && dataForm.flag === 'SUBMIT' && dataForm.isRecheck === 'YES'"
        type="success"
        @click="confirmSheet(dataForm.purchaseId)"
        >审 核</el-button
      >
    </div>
  </el-form>
</template>

<script>
import { computeVal } from '@/api/material-system/common'
import { getToken } from '@/utils/auth'
import { confirmPurchaseSheet, editPurchaseSheet, getPurchaseSheet } from '@/api/material-system/shop/purchase-sheet'
import { listPageV2 } from '@/api/auxiliaryFittings/supplier'
import { getWebsit } from '@/api/customerManagement.js'
import { storageListPageV2 } from '@/api/storage'
export default {
  name: 'PurchaseArea',
  props: {
    inputParam: {
      type: Object,
      default: function () {
        return {
          openType: 'add',
          purchaseId: ''
        }
      }
    }
  },
  data() {
    const validateCost = (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()
    }
    const validateRecQty = (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()
    }
    const validateRecGiftQty = (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 {
      imageLoading: false,
      loading: true,
      baseURL: process.env.VUE_APP_BASE_API,
      myHeaders: { 'x-token': getToken() },
      dataForm: {
        purchaseId: '', // 单据ID
        websitId: '', // 网点ID
        websitName: '', // 网点名称
        venderId: '', // 供应商ID
        storageId: '',
        venderName: '', // 供应商名称
        purchaseTime: '', // 采购日期
        imageUrl: '',
        notes: '', // 备注
        flag: '',
        items: [] // 关系辅材列表
      },
      dataFormRules: {
        storageId: [{ require: true, message: '请选择采购日期', trigger: 'blur' }],
        purchaseTime: [{ require: true, message: '请选择采购日期', trigger: 'blur' }],
        cost: [{ validator: validateCost, trigger: 'blur' }],
        recQty: [{ validator: validateRecQty, trigger: 'blur' }],
        recGiftQty: [{ validator: validateRecGiftQty, trigger: 'blur' }]
      },
      orgDataForm: {},
      goodsList: [], // 商品列表
      venderList: [], // 供应商列表
      innerVisible: false,
      searchGoods: '',
      saveBtn: false, // 保存按钮状态
      authShop: [],
      cangkuList: []
    }
  },
  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.getDetail()
    this.getVenderList()
    getWebsit({ type: 'C', status: true }).then(res => {
      this.authShop = res.data
    })
  },
  methods: {
    getDetail(id) {
      this.loading = true
      const openType = this.inputParam.openType
      const purchaseId = id || this.inputParam.purchaseId
      if (openType !== 'add') {
        getPurchaseSheet({ purchaseId }).then(res => {
          this.setDataForm(res.data)
          this.loading = false
        })
      } else {
        this.loading = false
      }
    },
    cancelForm() {
      this.$parent.backUpdPage()
    },
    submitForm(type) {
      if (this.dataForm.items && this.dataForm.items.length === 0) {
        this.$errorMsg('请添加商品后再保存！')
        return
      }
      this.$refs.dataForm.validate(valid => {
        if (!this.dataForm.imageUrl) {
          this.$errorMsg('请添加附件图片')
          return
        }
        if (valid) {
          if (type === 'edit') {
            editPurchaseSheet(this.dataForm).then(() => {
              this.getDetail(this.dataForm.purchaseId)
              this.$successMsg('保存成功')
            })
          }
        }
      })
    },
    setDataForm(data) {
      this.dataForm = {
        ...data
      }

      storageListPageV2({
        pageNum: 1,
        pageSize: -1,
        params: [
          { param: 'a.websit_id', compare: '=', value: data.websitId },
          {
            param: 'a.type',
            compare: 'like',
            value: '辅材'
          },
          { param: 'a.status', compare: '=', value: 'true' }
        ]
      }).then(res => {
        this.cangkuList = res.data.records
        this.dataForm.storageId = this.cangkuList?.[0]?.storageId || ''
      })
      Object.assign(this.orgDataForm, this.dataForm)
    },
    // 获取供应商列表
    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
      })
    },
    // 预估进价或申请数量变动
    changeCostValue(index, row) {
      computeVal({
        frontVal: row.applyQty,
        afterVal: row.applyCost,
        operator: '*',
        scale: 2
      }).then(res => {
        this.dataForm.items[index].applyCostValue = res.data
      })
    },
    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 (column.property === 'applyCostValue') {
          let count = 0
          sums[index] = values.reduce((prev, curr) => {
            const suffix = (curr + '').split('.')
            if (suffix.length > 1) {
              count = suffix[1].length > count ? suffix[1].length : count
            }
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = parseFloat(sums[index]).toFixed(count)
        }
      })
      return sums
    },
    // 上传成功回调
    uploadSuccess(res) {
      this.imageLoading = false
      this.dataForm.imageUrl = res.data.url
    },
    // 上传前检查
    beforeUpload(file) {
      if (this.imageLoading) {
        this.$errorMsg('文件上传中，稍后再试!')
        return false
      }
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const whiteList = ['jpg', 'jpeg', 'png']
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$errorMsg('只支持上传jpg/png文件!')
        return false
      }
      this.imageLoading = true
    },
    uploadError() {
      this.imageLoading = false
    },
    // 审核 采购入库单
    confirmSheet(purchaseId) {
      this.$confirm(
        `此操作将审核 ${purchaseId} 单据，<span style="color: #ff0000;">当前内容如果已修改将忽略保存</span>，是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }
      )
        .then(() => {
          this.loading = true
          confirmPurchaseSheet({ purchaseId: purchaseId }).then(
            () => {
              setTimeout(() => {
                this.inputParam.openType = 'view'
                this.getDetail(purchaseId)
                this.$successMsg('审核成功')
                this.loading = false
              }, 2000)
            },
            () => {
              this.loading = false
            }
          )
        })
        .catch(() => console.log('取消'))
    }
  }
}
</script>

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