<template>
  <template-page
    ref="pageRef"
    :get-list="getList"
    :export-list="exportList"
    :operation="operation()"
    :table-events="tableEvents"
    :table-attributes="tableAttributes"
    :options-evens-group="optionsEvensGroup"
    :column-parsing="columnParsing"
  >
    <el-dialog title="价格类型" :visible.sync="visible" width="40%" :append-to-body="true" @close="handleClose">
      <el-form ref="formData" :model="formData" :rules="formRules" label-width="120px" :inline="false" size="mini" :disabled="disabled">
        <el-form-item label="销售类型名称" prop="saleId">
          <el-select v-model="formData.saleId" placeholder="请选择销售类型名称" clearable filterable @change="handleChange">
            <el-option
              v-for="item in saleypeList"
              :key="item.id"
              :label="item.saleName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="销售类型编码" prop="saleCode">
          <el-input v-model="formData.saleCode" disabled placeholder="请选择销售类型生成" />
        </el-form-item>
        <el-form-item label="价格类型" prop="priceTypeId">
          <el-select v-model="formData.priceTypeId" placeholder="请选择价格类型" clearable filterable>
            <el-option
              v-for="item in priceTypeList"
              :key="item.priceTypeId"
              :label="item.priceTypeName"
              :value="item.priceTypeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="返利钱包" prop="walletId2">
          <el-select v-model="formData.walletId2" placeholder="请选择返利钱包名称" clearable filterable>
            <el-option
              v-for="item in rebateWalletList"
              :key="item.walletRebateId"
              :label="item.name"
              :value="item.walletRebateId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="钱包" prop="walletId">
          <el-select v-model="formData.walletId" placeholder="请选择钱包名称" clearable filterable>
            <el-option
              v-for="item in walletList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-switch v-model="formData.status" :active-value="true" :inactive-value="false" />
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :disabled="disabled" @click="handleSubmit">确定</el-button>
      </span>
    </el-dialog>
  </template-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import add_callback_mixin from '@/components/template/add_callback_mixin.js'
import Popu from '@/components/template/popu.vue'
import { saleTypeRebateListV2, getNoRebateWalletList, getWalletList } from '@/api/policy_list'
import {
  getProductPriceListV2,
  getPriceSalesRelaListV2,
  exportPriceSalesRelaListV2,
  addPriceSalesRela,
  editPriceSalesRela,
  updatePriceSalesRelaStatus,
  getPriceSalesRelaDetail,
  delPriceSalesRela
} from '@/api/priceType'
export default {
  components: { TemplatePage, Popu },
  mixins: [import_mixin, add_callback_mixin],
  data() {
    return {
      visible: false,
      // 事件组合
      optionsEvensGroup: [
        [
          [
            {
              name: '新增',
              click: this.addOn(() => {
                this.handleShow()
              })
              // isRole: this.$checkBtnRole('add', this.$route.meta.roles)
            }
          ]
        ],
        [
          [
            {
              name: '批量删除',
              click: async() => {
                if (this.recordSelected.length === 0) {
                  this.$message.error('请选择需要删除的数据')
                  return
                }
                const ids = this.recordSelected.map(v => {
                  return v.priceSaleTypeRelaId
                })
                const params = ids
                await delPriceSalesRela(params)
                this.$refs.pageRef.refreshList()
                this.$message.success('批量删除成功')
              }
            }
          ]
        ]
      ],
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true
      }, // 关闭新增弹窗

      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      recordSelected: [],
      edit: false,
      disabled: false,
      formData: {
        priceTypeId: '',
        saleId: '',
        saleCode: '',
        walletId: '',
        walletName: '',
        walletId2: '',
        walletName2: '',
        status: true
      },
      formRules: {
        priceTypeId: [{ required: true, message: '请选择', trigger: 'change' }],
        saleId: [{ required: true, message: '请选择', trigger: 'change' }],
        saleCode: [{ required: true, message: '请选择', trigger: 'change' }],
        walletId: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      priceTypeList: [],
      saleypeList: [],
      walletList: [],
      rebateWalletList: []
    }
  },
  methods: {
    // 列表请求函数
    getList(...p) {
      this.recordSelected = []
      return getPriceSalesRelaListV2(...p)
    },
    // 列表导出函数
    exportList: exportPriceSalesRelaListV2,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      if (item.colName === 'status') {
        defaultData.render = (h, { row, index, column }) => {
          return (
            <div>
              <el-switch
                value={row.status}
                onInput={value => (row.status = value)}
                active-value='有效'
                inactive-value='无效'
                onChange={() => {
                  updatePriceSalesRelaStatus({
                    priceSaleTypeRelaId: row.priceSaleTypeRelaId,
                    status: row.status === '有效' ? 'ON' : 'OFF'
                  }).then(res => {
                    this.$successMsg('状态更改成功')
                  })
                }}
              ></el-switch>
              <span style='margin-left:10px'>{row.statusMap && row.statusMap[row.status]}</span>
            </div>
          )
        }
      }
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    operation() {
      return (h, { row, index, column }) => {
        return (
          <div class='operation-btns'>
            <el-button
              type='text'
              size='default'
              onClick={ async() => {
                this.getDetail(row.priceSaleTypeRelaId)
                this.disabled = true
                this.handleShow()
              }}
            >详情</el-button>
            <el-button
              type='text'
              size='default'
              onClick={ async() => {
                this.getDetail(row.priceSaleTypeRelaId)
                this.edit = true
                this.handleShow()
              }}
            >编辑</el-button>
            <el-popconfirm
              onConfirm={() => {
                delPriceSalesRela([row.priceSaleTypeRelaId]).then(res => {
                  this.$successMsg('删除成功')
                  this.$refs.pageRef.refreshList()
                })
              }}
              title='是否确定需要删除该项内容?'
            >
              <el-button slot='reference' size='mini' type='text'>
                  删除
              </el-button>
            </el-popconfirm>
          </div>
        )
      }
    },
    handleClose() {
      this.edit = false
      this.disabled = false
      this.$refs.formData.resetFields()
      this.addOff(() => {
        this.visible = false
      })()
    },
    handleShow() {
      this.visible = true
      this.getProductPriceListV2()
      this.getSaleTypeRebateListV2()
      this.getNoRebateWalletList()
      this.getWalletList()
    },
    handleChange(e) {
      if (e) {
        this.formData.saleCode = this.saleypeList.find(k => k.id === e).saleCode
      } else {
        this.formData.saleCode = ''
      }
    },
    handleWalletChange(e) {
      if (e) {
        this.formData.walletName = this.walletList.find(k => k.id === e).name
      } else {
        this.formData.walletName = ''
      }
    },
    handleWalletChange2(e) {
      if (e) {
        this.formData.walletName2 = this.rebateWalletList.find(k => k.walletRebateId === e).name
      } else {
        this.formData.walletName2 = ''
      }
    },
    getProductPriceListV2() {
      getProductPriceListV2({
        'pageNum': 1,
        'pageSize': -1,
        'params': []
      }).then(res => {
        this.priceTypeList = res.data.records
      })
    },
    getSaleTypeRebateListV2() {
      saleTypeRebateListV2({
        'pageNum': 1,
        'pageSize': -1,
        'params':
          [
            {
              'param': 'a.status',
              'compare': '=',
              'value': 'true'
            }
          ]

      }).then(res => {
        this.saleypeList = res.data.records
      })
    },
    getNoRebateWalletList() {
      getNoRebateWalletList({
        walletName: ''
      }).then(res => {
        this.walletList = res.data
      })
    },
    getWalletList() {
      getWalletList({
        pageNum: 1,
        pageSize: -1,
        name: '',
        status: true
      }).then(res => {
        this.rebateWalletList = res.data.records
      })
    },
    async getDetail(priceSaleTypeRelaId) {
      const { data } = await getPriceSalesRelaDetail({ priceSaleTypeRelaId })
      this.formData = { ...data }
    },
    handleSubmit() {
      this.$refs.formData.validate(valid => {
        if (valid) {
          const params = {
            ...this.formData
          }
          if (this.formData.walletId2) {
            params.walletName2 = this.rebateWalletList.find(k => k.walletRebateId === this.formData.walletId2).name
            params.walletName = this.walletList.find(k => k.id === this.formData.walletId).name
          }
          if (!this.edit) {
            params.priceSaleTypeRelaId = ''
            addPriceSalesRela(params).then(res => {
              this.handleClose()
              this.$successMsg('新增成功')
              this.$refs.pageRef.refreshList()
            })
          } else {
            editPriceSalesRela(params).then(res => {
              this.edit = false
              this.handleClose()
              this.$successMsg('编辑成功')
              this.$refs.pageRef.refreshList()
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-select{
  width: 100%;
}
</style>
