<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="sheetId">
      <el-input disabled :value="dataForm.sheetId" />
    </el-form-item>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="网点" prop="shopId">
          <el-select v-model="dataForm.shopId" :disabled="formDisabled" placeholder="请选择网点" style="width: 100%">
            <el-option
              v-for="(item, index) in getAuthShop(null, dataForm)"
              :key="index"
              :label="shopLabelStrHandle(item)"
              :value="item.shopId"
            />
          </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="vendorLabelStrHandle(item)"
              :value="item.venderId"
            />
          </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="estimateCost" label="预估进价" header-align="left" align="center">
            <template slot-scope="{ $index, row }">
              <label v-if="inputParam.openType === 'view'">{{ row.estimateCost + ' 元/' + row.measureUnit }}</label>
              <el-form-item
                v-else
                style="margin: 18px 0"
                label-width="0"
                size="mini"
                :prop="'items.' + $index + '.estimateCost'"
                :rules="dataFormRules.estimateCost"
              >
                <el-input v-model="row.estimateCost" size="mini" @change="changeCostValue($index, row)">
                  <template slot="suffix">{{ ' 元/' + row.measureUnit }}</template>
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="purchaseQty" label="订货数量" header-align="left" align="center" width="120">
            <template slot-scope="{ $index, row }">
              <label v-if="inputParam.openType === 'view'">{{ row.purchaseQty + ' /' + row.measureUnit }}</label>
              <el-form-item
                v-else
                style="margin: 18px 0"
                label-width="0"
                size="mini"
                :prop="'items.' + $index + '.purchaseQty'"
                :rules="dataFormRules.purchaseQty"
              >
                <el-input v-model="row.purchaseQty" size="mini" @change="changeCostValue($index, row)">
                  <template slot="suffix">{{ ' /' + row.measureUnit }}</template>
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="estimateCostValue" label="预估金额" header-align="left" align="center">
            <template slot-scope="{ $index, row }">
              <label>{{ row.estimateCostValue + ' 元' }}</label>
            </template>
          </el-table-column>
          <el-table-column prop="measureUnit" label="采购单位" />
          <el-table-column prop="unitQty" label="转换系数" />
          <el-table-column prop="salesUnit" label="售卖单位" />
          <el-table-column prop="productModel" label="商品型号" min-width="100" />
          <el-table-column prop="specification" 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="checkBtn('add')" type="primary" :disabled="saveBtn" @click="submitForm('add')">保 存</el-button>
      <el-button v-if="checkBtn('edit')" type="primary" :disabled="saveBtn" @click="submitForm('edit')"
        >保 存</el-button
      >
      <el-button v-if="checkBtn('submit')" type="success" @click="submitSheet(dataForm.sheetId)">提 交</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="
          goodsList.filter(
            data =>
              !searchGoods ||
              data.goodsName.toLowerCase().includes(searchGoods.toLowerCase()) ||
              data.specification.toLowerCase().includes(searchGoods.toLowerCase())
          )
        "
        :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="productModel" label="商品型号" />
        <el-table-column prop="specification" label="规格" />
        <el-table-column prop="qty" 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 { getVenderGoodsList, getVenderList } from '@/api/material-system/vender'
import { computeVal } from '@/api/material-system/common'

export default {
  name: 'PurchaseApplyArea',
  props: {
    inputParam: {
      type: Object,
      default: function () {
        return {
          openType: 'add',
          sheetId: ''
        }
      }
    }
  },
  data() {
    const validatePurchaseQty = (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: {
        sheetId: '', // 单据ID
        shopId: '', // 网点ID
        shopName: '', // 网点名称
        venderId: '', // 供应商ID
        venderName: '', // 供应商名称
        notes3: '', // 备注
        flag: '',
        items: [] // 关系辅材列表
      },
      dataFormRules: {
        shopId: [{ required: true, message: '请选择网点', trigger: 'change' }],
        purchaseQty: [{ validator: validatePurchaseQty, trigger: 'blur' }]
      },
      goodsList: [], // 商品列表
      venderList: [], // 供应商列表
      innerVisible: false,
      searchGoods: '',
      saveBtn: false // 保存按钮状态
    }
  },
  computed: {
    formDisabled() {
      return this.inputParam.openType === 'view' || this.dataForm.sheetId !== ''
    },
    goodsTotalCount: function () {
      return this.dataForm && this.dataForm.items ? this.dataForm.items.length : 0
    }
  },
  watch: {
    // 网点变动重新执行辅材获取资料
    'shopPurchaseForm.shopId': function () {
      this.getVenderGoodsList(this.dataForm.venderId)
    },
    searchGoods: function () {
      this.$refs.goodsTable.clearSelection()
    }
  },
  mounted() {
    this.getVenderList()
    this.getDetail()
  },
  methods: {
    getDetail(id) {
      this.loading = true
      const openType = this.inputParam.openType
      const sheetId = id || this.inputParam.sheetId
      if (openType !== 'add') {
        getPurchaseApplySheet({ sheetId }).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.getList()
      this.$emit('update:isOpen', false)
    },
    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('保存成功')
            })
          } else {
            this.dataForm.shopName = this.getArraysName(this.authShop, this.dataForm, 'shopId', 'shopName')
            this.dataForm.venderName = this.getArraysName(this.venderList, this.dataForm, 'venderId', 'venderName')
            addPurchaseApplySheet(this.dataForm).then(res => {
              this.inputParam.openType = 'edit'
              this.setDataForm(res.data)
              this.$successMsg('保存成功')
            })
          }
        }
      })
    },
    setDataForm(data) {
      this.dataForm = {
        sheetId: data.sheetId, // 单据编号
        shopId: data.shopId, // 网点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 === 0 && this.inputParam.openType === type,
        revoke: this.dataForm.flag === 1,
        submit: this.dataForm.flag === 0 && this.dataForm.sheetId !== ''
      }
      // 检查按钮权限
      return this.checkBtnRole(type) && typeMap[type]
    },
    // 获取供应商列表
    getVenderList() {
      getVenderList({ pageNum: 1, pageSize: -1, flag: 1 }).then(res => {
        this.venderList = res.data.records
      })
    },
    // 获取供应商关系辅材列表
    getVenderGoodsList(val, clear = true) {
      if (clear) {
        this.dataForm.items = []
      }
      getVenderGoodsList({
        pageNum: 1,
        pageSize: -1,
        venderId: val,
        flag: 1,
        status: 1,
        shopId: this.dataForm.shopId
      }).then(res => {
        this.goodsList = res.data.records
      })
    },
    // 选中辅材添加到表单中
    selGoods() {
      this.searchGoods = ''
      this.$refs.goodsTable.selection.forEach(value => {
        const index = this.dataForm.items.findIndex(item => {
          return item.goodsId === value.goodsId
        })
        // 添加不在列表的商品
        if (index < 0) {
          this.dataForm.items.push({
            goodsId: value.goodsId,
            goodsName: value.goodsName,
            ndays: value.ndays,
            purchaseQty: 0,
            estimateCost: 0,
            estimateCostValue: 0,
            measureUnit: value.measureUnit,
            unitQty: value.unitQty,
            salesUnit: value.salesUnit,
            productModel: value.productModel,
            specification: value.specification
          })
        }
      })
      this.$refs.goodsTable.clearSelection()
      this.innerVisible = false
    },
    // 删除明细
    delItem(index) {
      this.dataForm.items.splice(index, 1)
    },
    getRowKeys(row) {
      return row.goodsId
    },
    // 提交 采购申请单
    submitSheet(sheetId) {
      this.$confirm(
        `此操作将提交 ${sheetId} 单据，<span style="color: #ff0000;">当前内容如果已修改将忽略保存</span>，是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }
      )
        .then(() => {
          this.loading = true
          submitPurchaseApplySheet({ sheetId: sheetId }).then(
            () => {
              setTimeout(() => {
                this.inputParam.openType = 'view'
                this.getDetail(sheetId)
                this.$successMsg('提交成功')
                this.loading = false
              }, 2000)
            },
            () => {
              this.loading = false
            }
          )
        })
        .catch(() => console.log('取消'))
    },
    // 预估进价或申请数量变动
    changeCostValue(index, row) {
      computeVal({
        frontVal: row.purchaseQty,
        afterVal: row.estimateCost,
        operator: '*',
        scale: 4
      }).then(res => {
        this.dataForm.items[index].estimateCostValue = 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 === 'estimateCostValue') {
          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>
