<template>
  <el-form
    ref="dataForm"
    v-loading="loading"
    class="form"
    :model="dataForm"
    :rules="dataFormRules"
    label-position="left"
    label-width="80px"
  >
    <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%"
            @change="getVenderGoodsList"
          >
            <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 label="备注" prop="notes3">
      <el-input
        v-model="dataForm.notes3"
        autocomplete="off"
        placeholder="备注"
        :disabled="inputParam.openType === 'view'"
      />
    </el-form-item>
    <el-row>
      <el-col>
        <el-divider>采购明细</el-divider>
      </el-col>
      <el-col>
        <el-button
          size="small"
          :disabled="inputParam.openType === 'view' || goodsList.length === 0"
          @click="innerVisible = true"
          >添加商品</el-button
        >
        <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="applyCost" label="预估进价" header-align="left" align="center">
            <template slot-scope="{ $index, row }">
              <label v-if="inputParam.openType === 'view'">{{ row.applyCost + ' 元/' + row.goodsStockUnit }}</label>
              <el-form-item
                v-else
                style="margin: 18px 0"
                label-width="0"
                size="mini"
                :prop="'items.' + $index + '.applyCost'"
                :rules="dataFormRules.applyCost"
              >
                <el-input v-model="row.applyCost" 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="applyQty" label="订货数量" header-align="left" align="center" width="120">
            <template slot-scope="{ $index, row }">
              <label v-if="inputParam.openType === 'view'">{{ row.applyQty + ' /' + row.goodsStockUnit }}</label>
              <el-form-item
                v-else
                style="margin: 18px 0"
                label-width="0"
                size="mini"
                :prop="'items.' + $index + '.applyQty'"
                :rules="dataFormRules.applyQty"
              >
                <el-input v-model="row.applyQty" 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="applyCostValue" label="预估金额" header-align="left" align="center">
            <template slot-scope="{ $index, row }">
              <label>{{ row.applyCostValue + ' 元' }}</label>
            </template>
          </el-table-column>
          <el-table-column prop="goodsStockUnit" label="采购单位" />
          <el-table-column prop="goodsSpecification" label="规格" min-width="80" />
          <el-table-column v-if="inputParam.openType !== 'view'" fixed="right" align="center" label="">
            <template slot-scope="scope">
              <el-button type="text" @click="delItem(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row style="margin-top: 15px">
          <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('add') && inputParam.openType == 'add'"
        type="primary"
        :disabled="saveBtn"
        @click="submitForm('add')"
        >保 存</el-button
      >
      <el-button
        v-if="
          $restrict('edit') && dataForm.flag === 'SAVE' && dataForm.isRecheck === 'NO' && inputParam.openType == 'edit'
        "
        type="primary"
        :disabled="saveBtn"
        @click="submitForm('edit')"
        >保 存</el-button
      >
      <el-button
        v-if="$restrict('submit') && dataForm.flag === 'SAVE' && dataForm.isRecheck === 'NO'"
        type="success"
        @click="submitSheet(dataForm.purchaseId)"
        >提 交</el-button
      >
    </div>
    <el-dialog
      width="70%"
      title="商品列表"
      :visible.sync="innerVisible"
      :close-on-click-modal="false"
      @close="$refs.goodsTable.clearSelection()"
    >
      <el-input
        v-model="searchGoods"
        size="small"
        placeholder="输入 辅材名称 或 规格 模糊搜索"
        style="margin-bottom: 5px"
        :clearable="true"
      />
      <el-table
        ref="goodsTable"
        :data="showgoodsList"
        :row-key="getRowKeys"
        height="400"
        size="mini"
        border
        header-cell-class-name="headerRowColor"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" :reserve-selection="true" />
        <el-table-column prop="goodsId" label="辅材编号" />
        <el-table-column prop="goodsCode" label="辅材代码" />
        <el-table-column prop="goodsName" label="辅材名称" />
        <el-table-column prop="categoryName" label="小类名称" />
        <el-table-column prop="goodsSpecification" label="规格" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="selGoods">确 定</el-button>
      </div>
    </el-dialog>
  </el-form>
</template>

<script>
import {
  addPurchaseApplySheet,
  submitPurchaseApplySheet,
  editPurchaseApplySheet,
  getPurchaseApplySheet
} from '@/api/material-system/shop/purchase-apply-sheet'
import { getNewVenderGoodsList } from '@/api/material-system/vender'
import { computeVal } from '@/api/material-system/common'
import { listPageV2 } from '@/api/auxiliaryFittings/supplier'
import { getWebsit } from '@/api/customerManagement.js'
export default {
  name: 'PurchaseApplyArea',
  props: {
    inputParam: {
      type: Object,
      default: function () {
        return {
          openType: 'add',
          purchaseId: ''
        }
      }
    }
  },
  data() {
    const validateapplyQty = (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: {
        purchaseId: '', // 单据ID
        websitId: '', // 网点ID
        websitName: '', // 网点名称
        venderId: '', // 供应商ID
        venderName: '', // 供应商名称
        notes3: '', // 备注
        flag: '',
        items: [] // 关系辅材列表
      },
      dataFormRules: {
        websitId: [{ required: true, message: '请选择网点', trigger: 'change' }],
        applyQty: [{ validator: validateapplyQty, trigger: 'blur' }]
      },
      goodsList: [], // 商品列表
      venderList: [], // 供应商列表
      innerVisible: false,
      searchGoods: '',
      saveBtn: false, // 保存按钮状态
      authShop: []
    }
  },
  computed: {
    showgoodsList() {
      return (
        this?.goodsList?.filter(
          data =>
            !this.searchGoods ||
            !!~data.goodsName.indexOf(this.searchGoods) ||
            !!~data.goodsSpecification.indexOf(this.searchGoods)
        ) || []
      )
    },
    formDisabled() {
      return this.inputParam.openType === 'view' || this.dataForm.purchaseId !== ''
    },
    goodsTotalCount: function () {
      return this.dataForm && this.dataForm.items ? this.dataForm.items.length : 0
    }
  },
  watch: {
    // 网点变动重新执行辅材获取资料
    'shopPurchaseForm.websitId': function () {
      this.getVenderGoodsList(this.dataForm.venderId)
    },
    searchGoods: function () {
      this.$refs.goodsTable.clearSelection()
    }
  },
  mounted() {
    this.getDetail()
    this.getVenderList()
    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 purchaseId = id || this.inputParam.purchaseId
      if (openType !== 'add') {
        getPurchaseApplySheet({ purchaseId }).then(res => {
          this.setDataForm(res.data)
          if (openType !== 'view') {
            this.getVenderGoodsList(res.data.venderId, false)
          }
          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 (valid) {
          if (type === 'edit') {
            editPurchaseApplySheet(this.dataForm).then(() => {
              this.$successMsg('保存成功')
              this.cancelForm()
            })
          } else {
            this.dataForm.websitName = this.authShop.find(item => item.websitId === this.dataForm.websitId)?.name
            this.dataForm.venderName = this.venderList.find(
              item => item.venderId === this.dataForm.venderId
            )?.venderName
            addPurchaseApplySheet(this.dataForm).then(res => {
              this.$successMsg('保存成功')
              this.cancelForm()
            })
          }
        }
      })
    },
    setDataForm(data) {
      this.dataForm = {
        ...data
      }
    },
    // 获取供应商列表
    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
      })
    },
    // 获取供应商关系辅材列表
    getVenderGoodsList(val, clear = true) {
      if (clear) {
        this.dataForm.items = []
      }
      if (val) {
        getNewVenderGoodsList({
          pageNum: 1,
          pageSize: -1,
          params: [
            { param: 'a.vender_id', compare: '=', value: val },
            { param: 'a.rela_status', compare: '=', value: 'ON' }
          ]
        }).then(res => {
          this.goodsList = res.data.records
        })
      }
    },
    // 选中辅材添加到表单中
    selGoods() {
      this.searchGoods = ''
      this.$refs.goodsTable.selection.forEach(value => {
        // 添加不在列表的商品
        if (
          !this.dataForm.items.find(item => {
            return item.goodsId === value.goodsId
          })
        ) {
          this.dataForm.items.push({
            goodsId: value.goodsId,
            goodsName: value.goodsName,
            goodsSpecification: value.goodsSpecification,
            applyQty: 0,
            applyCost: 0,
            applyCostValue: 0,
            goodsStockUnit: value.goodsStockUnit
          })
        }
      })
      this.$refs.goodsTable.clearSelection()
      this.innerVisible = false
    },
    // 删除明细
    delItem(index) {
      this.dataForm.items.splice(index, 1)
    },
    getRowKeys(row) {
      return row.goodsId
    },
    // 提交 采购申请单
    submitSheet(purchaseId) {
      this.$confirm(
        `此操作将提交 ${purchaseId} 单据，<span style="color: #ff0000;">当前内容如果已修改将忽略保存</span>，是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }
      )
        .then(() => {
          this.loading = true
          submitPurchaseApplySheet({ purchaseId: purchaseId }).then(
            () => {
              setTimeout(() => {
                this.inputParam.openType = 'view'
                this.getDetail(purchaseId)
                this.$successMsg('提交成功')
                this.loading = false
              }, 2000)
            },
            () => {
              this.loading = false
            }
          )
        })
        .catch(() => console.log('取消'))
    },
    // 预估进价或申请数量变动
    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
    }
  }
}
</script>

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