<template>
  <section class="productRecommend">
    <ai-list>
      <ai-title slot="title" title="推荐产品" isShowBottomBorder isShowBack @onBackClick="$router.push({query:{}})"/>
      <template #content>
        <ai-search-bar>
          <template #left>
            <el-button type="primary" @click="dialog=true">新增推荐</el-button>
            <ai-select placeholder="机构类型" v-model="search.organizationType" @change="page.current=1,getTableData()"
                       :selectList="dict.getDict('financialOrganizationType')"/>
          </template>
        </ai-search-bar>
        <ai-table :tableData="tableData" :total="page.total" :current.sync="page.current" :size.sync="page.size"
                  @getList="getTableData" :col-configs="colConfigs" :dict="dict">
          <el-table-column slot="options" label="操作" fixed="right" align="center" width="200px">
            <template slot-scope="{row}">
              <el-button type="text" @click="handleEdit(row)">编辑</el-button>
              <el-button type="text" @click="handleDelete(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </ai-table>
      </template>
    </ai-list>
    <ai-dialog :visible.sync="dialog" :title="dialogTitle" @closed="form={}" @onConfirm="submitAudit" width="560px">
      <el-form :model="form" :rules="rules" ref="PRForm" size="small" label-width="120px">
        <el-form-item label="机构类型" prop="organizationType">
          <ai-select v-model="form.organizationType" :selectList="dict.getDict('financialOrganizationType')"
                     @change="getProducts(),form.productId=null"/>
        </el-form-item>
        <el-form-item label="推荐产品" prop="productId">
          <ai-select v-model="form.productId" :selectList="productOps" @change="getOrgId"/>
        </el-form-item>
        <el-form-item label="推荐顺序" prop="showIndex">
          <el-input type="number" v-model.number="form.showIndex" placeholder="请输入" clearable/>
        </el-form-item>
      </el-form>
    </ai-dialog>
  </section>
</template>

<script>
import {mapState} from "vuex";

export default {
  name: "productRecommend",
  props: {
    instance: Function,
    dict: Object,
    permissions: Function
  },
  computed: {
    ...mapState(['user']),
    isFinanceUser() {
      return !!this.user.financeUser?.id
    },
    dialogTitle() {
      return this.form.id ? "编辑推荐" : "新增推荐"
    },
    productOps() {
      return this.productList.map(e => ({dictName: e.productName, dictValue: e.id})) || []
    }
  },
  data() {
    return {
      search: {productName: ""},
      page: {current: 1, size: 10, total: 0},
      tableData: [],
      colConfigs: [
        {label: "产品名称", prop: "productName"},
        {label: "机构类型", prop: "organizationType", dict: "financialOrganizationType", width: 120},
        {label: "推荐顺序", prop: "showIndex", align: "center", width: 120},
        {label: "机构名称", prop: "organizationName"},
        {slot: "options"}
      ],
      dialog: false,
      form: {},
      rules: {
        showIndex: [
          {required: true, message: "请输入推荐顺序"},
          {pattern: /^[1-7]$/, message: "请输入1~7之间的整数"}
        ],
        productId: [{required: true, message: "请选择推荐产品", trigger: "blur"}],
        organizationType: [{required: true, message: "请选择机构类型"}],
      },
      productList: []
    }
  },
  methods: {
    getTableData() {
      this.instance.post("/appfinancialproductrecommend/list", null, {
        params: {...this.page, ...this.search}
      }).then(res => {
        if (res?.data) {
          this.tableData = res.data?.records
          this.page.total = res.data.total
        }
      })
    },
    handleEdit(row) {
      this.dialog = true
      this.form = JSON.parse(JSON.stringify(row))
      this.getProducts()
    },
    handleDelete(ids) {
      this.$confirm("是否要删除该推荐?").then(() => {
        this.instance.post("/appfinancialproductrecommend/delete", null, {
          params: {ids}
        }).then(res => {
          if (res?.code == 0) {
            this.$message.success("删除成功!")
            this.getTableData()
          }
        })
      }).catch(() => 0)
    },
    submitAudit() {
      this.$refs.PRForm.validate(v => {
        if (v) {
          this.instance.post("/appfinancialproductrecommend/addOrUpdate", this.form).then(res => {
            if (res?.code == 0) {
              this.$message.success("提交成功!")
              this.getTableData()
              this.dialog = false
            }
          })
        }
      })
    },
    getProducts() {
      let {organizationType} = this.form
      this.instance.post("/appfinancialproduct/list", null, {
        params: {organizationType, size: 999, status: 1}
      }).then(res => {
        if (res?.data) {
          this.productList = res.data?.records
        }
      })
    },
    getOrgId(productId) {
      let product = this.productList.find(e => e.id == productId)
      this.form.organizationId = product?.organizationId || ""
      this.$forceUpdate()
    }
  },
  created() {
    this.getTableData()
  }
}
</script>

<style lang="scss" scoped>
.productRecommend {
  height: 100%;

  ::v-deep input[type="number"] {
    line-height: 1px !important;

    &::-webkit-outer-spin-button, &::-webkit-inner-spin-button {
      -webkit-appearance: none !important;
    }
  }
}
</style>
