import uniq from 'lodash/uniq'
import { multiplied, plus } from '@/utils/bignumber'
import { Modal } from 'ant-design-vue'
import { apiPurchase } from '@/api/daodi'

/**
 * 道地药材和市场交易区采购的公用方法
 */
export default {
  data() {
    return {
      selectAll: false,
      mVisible: false
    }
  },
  computed: {
    selectedGoods() {
      return this.selectedRowKeys.length || 0
    },
    selectedGoodsAmount() {
      const selectedProd = this.prodList.filter(prod => this.selectedRowKeys.includes(prod.id))
      if (selectedProd.length === 0) return 0
      const priceStrategies = {
        // 一口价
        1: (prev, cur) => {
          const curAmount = multiplied(cur.salesPrice, cur.purchaseQuantity || 0)
          return plus(prev, curAmount)
        },
        // 阶梯价格
        2: (prev, cur) => {
          const { purchaseQuantity, wholesalePrices } = cur
          // eslint-disable-next-line array-callback-return
          const adaptiveWholesalePrice = wholesalePrices.find(item => {
            const purchaseQuantityGTQuantityMin = +purchaseQuantity >= +item.quantityMin
            const purchaseQuantityLTQuantityMax =
              +purchaseQuantity <= +item.quantityMax || !item.quantityMax
            if (purchaseQuantityGTQuantityMin && purchaseQuantityLTQuantityMax) {
              return item
            }
          })
          const curAmount = multiplied(adaptiveWholesalePrice?.price || 0, purchaseQuantity || 0)
          return plus(prev, curAmount)
        }
      }
      return selectedProd.reduce((prev, cur) => {
        return priceStrategies[cur.priceType](prev, cur)
      }, 0)
    }
  },
  methods: {
    /** 商品选中事件 */
    onSelectChange({ id }, val) {
      if (val) {
        this.selectedRowKeys.push(id)
      } else {
        const selectIndex = this.selectedRowKeys.findIndex(e => e === id)
        this.selectedRowKeys.splice(selectIndex, 1)
      }
    },
    clearSelectedRowKeys() {
      this.selectedRowKeys = []
    },
    /** 全选 */
    handleSelectAll(checked) {
      if (!checked) {
        this.selectAll = false
        this.clearSelectedRowKeys()
        return
      }
      const availableProd = this.prodList.filter(e => !e.purchaseDisabled)
      const withoutPurchaseQtyProd = availableProd.filter(e => !e.purchaseQuantity) // 得到未填写采购数量商品
      if (withoutPurchaseQtyProd.length !== 0) {
        withoutPurchaseQtyProd.forEach(prod => {
          this.$set(prod, 'purchaseQuantityValid', false)
        })
        return this.$message.error('请输入采购数量')
      }
      this.selectAll = true
      const prodIdList = availableProd.map(prod => prod.id)
      this.selectedRowKeys = uniq([...this.selectedRowKeys, ...prodIdList])
    },
    /** 采购数量变更 */
    handlePurchaseQuantityInput(id, val) {
      const prod = this.prodList.find(prod => prod.id === id)
      if (prod) {
        this.$set(prod, 'purchaseQuantity', val)
      }
    },
    /** 摘牌 */
    handelPurchase(typeName) {
      if (this.selectedRowKeys.length === 0) return this.$message.error('请选择摘牌产品')
      // 创建购销合同前校验
      const purchaseGoods = this.prodList.filter(prod => {
        return this.selectedRowKeys.includes(prod.id)
      })
      const errMsg = this.beforeCreateValid(purchaseGoods)
      if (errMsg) {
        console.warn(errMsg)
        this.$message.error(errMsg)
        return
      }
      const baoGongArr = purchaseGoods.filter(item => {
        return item.isBaoGong === true
      })
      // eslint-disable-next-line eqeqeq
      if (typeName == 'goodsDelist') {
        this.setGoodsDelistRecord(baoGongArr)
        this.setApiPurchase(purchaseGoods)
        return
      }
      if (baoGongArr.length === 1) {
        this.checkGoodsDelistRecord(baoGongArr)
      } else if (baoGongArr.length > 1) {
        this.$message.error('不可同时摘牌多个保供产品，请重新选择')
        return false
      } else {
        this.getConfirmPurchase(purchaseGoods)
      }
    },
    getConfirmPurchase(purchaseGoods) {
      Modal.confirm({
        cancelText: '再想想',
        content: '点击确认摘牌后，系统将创建购销合同',
        okText: '确认摘牌',
        title: '确认摘牌？',
        onOk: async () => {
          const data = {
            bizType: 0,
            goodsList: purchaseGoods.map(e => ({
              goodsId: e.id,
              delistedQuantity: e.purchaseQuantity
            }))
          }
          // 创建购销合同
          const result = await apiPurchase(data)
          const { code, msg, data: contractId } = result
          if (+code !== 0) {
            this.$message.error(msg)
          } else {
            this.goToTcmSaleContract(contractId)
          }
        }
      })
    },
    // 创建合同
    async setApiPurchase(purchaseGoods) {
      const data = {
        bizType: 0,
        goodsList: purchaseGoods.map(e => ({
          goodsId: e.id,
          delistedQuantity: e.purchaseQuantity
        }))
      }
      // 创建购销合同
      const result = await apiPurchase(data)
      const { code, msg, data: contractId } = result
      if (+code !== 0) {
        this.$message.error(msg)
      } else {
        this.goToTcmSaleContract(contractId)
      }
    },
    async setGoodsDelistRecord(baoGongArr) {
      const url = '/tcme/goodsDelistRecord/save'
      // eslint-disable-next-line no-unused-vars
      const response = await this.$fetch({
        url,
        method: 'post',
        params: {
          goodsId: baoGongArr[0]?.id || '', // -- 商品接口id
          goodsTitle: baoGongArr[0]?.goodsTitle || '', // -- 摘牌商品标题
          orgDelistedQuantity: baoGongArr[0]?.purchaseQuantity || '', // -- 企业当前摘牌量
          // orgId: baoGongArr[0]?.goodsTitle || '', //-- 当前摘牌企业id
          orgName: localStorage.getItem('orgName') || '' // -- 当前摘牌企业名称
        }
      })
    },
    async checkGoodsDelistRecord(baoGongArr) {
      const url = '/tcme/api/contract/gs/buyer/baoGong/check'
      const data = {
        bizType: 0,
        goodsList: baoGongArr.map(e => ({
          goodsId: e.id,
          delistedQuantity: e.purchaseQuantity
        }))
      }
      // 检查购销合同
      const response = await this.$fetch({
        url,
        method: 'post',
        params: data
      })
      if (response.code === 0) {
        this.mVisible = true
      } else {
        this.$message.error(response.msg)
      }
    },
    handleCancel() {
      this.mVisible = false
    },
    /**
     * 创建购销合同前校验
     * 1、validPurchaseQty 校验是否有选择了但未输入此阿狗数量但商品
     * @param purchaseGoods 勾选购买的商品
     * @return {string}
     */
    beforeCreateValid(purchaseGoods) {
      let errMsg = ''
      const validPurchaseQty = () => {
        let valid = true
        purchaseGoods.forEach(item => {
          if (!item.purchaseQuantity) {
            this.$set(item, 'purchaseQuantityValid', false)
            valid = false
          }
        })
        return valid ? '' : '请输入采购数量'
      }
      errMsg = validPurchaseQty()
      return errMsg
    },
    /**
     * 跳转到买家中心合同编辑页
     * @param id 合同id
     * */
    goToTcmSaleContract(id) {
      Modal.confirm({
        cancelText: '稍后编辑',
        content: '与挂牌方确认交易信息后可以进行线上签订，双方签订完成后即可下单交易。',
        icon: () => this.$createElement('a-icon', { props: { type: 'exclamation-circle', theme: 'filled' } }),
        okText: '立即编辑',
        title: '已创建购销合同，请前往编辑买家信息',
        onOk: () => {
          // 有 id 表示是单个合同的情况，跳转到编辑页。否则跳转到买家起草中页面
          if (id) {
            return this.$router.push({
              path: '/buyer/tcm-sale-contract/contract-edit',
              query: {
                id,
                isEdit: true
              }
            })
          }
          this.$router.push({
            path: 'buyer/tcm-sale-contract/index?activeTab=0'
          })
        },
        // 注意 Modal 中的 this 指向
        onCancel: () => {
          Modal.confirm({
            class: 'daodi-mall__text--bold',
            content: '您可前往【我的工作台】-【合同管理】-【采购合同】起草中列表中，进行编辑。',
            icon: () => this.$createElement('a-icon', { props: { type: 'exclamation-circle', theme: 'filled' } }),
            okText: '我知道了'
          })
        }
      })
    }
  }
}
这是之前没有转换之前的代码直接放进主页面吧