<template>
    <basic-container>
        <avue-crud :option="option"
                   :table-loading="loading"
                   :data="data"
                   :page.sync="page"
                   :permission="permissionList"
                   :before-open="beforeOpen"
                   v-model="form"
                   ref="crud"
                   @row-update="rowUpdate"
                   @row-save="rowSave"
                   @row-del="rowDel"
                   @search-change="searchChange"
                   @search-reset="searchReset"
                   @selection-change="selectionChange"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @refresh-change="refreshChange"
                   @on-load="onLoad">
            <template slot="menuLeft">
                <el-button type="primary" size="small" icon="el-icon-plus"
                           v-if="permission.bussinessinfo_add"
                           @click="showAdd">新增
                </el-button>
                <el-button type="danger"
                           size="small"
                           icon="el-icon-delete"
                           plain
                           v-if="permission.productratestrategy_delete"
                           @click="handleDelete">删 除
                </el-button>
            </template>
            <template slot-scope="{row}" slot="menu">
                <el-button type="text" size="small" icon="el-icon-edit" plain class="none-border"
                           @click.stop="handleEdit(row)">编辑
                </el-button>
            </template>
        </avue-crud>
        <el-dialog title="产品添加" :append-to-body="true" :visible.sync="formVisible" top="1vh"
                   :close-on-click-modal="false" width="80%" @close="closeDialog">
            <avue-form :option="formOption" v-model="formObj" @submit="submit">
            </avue-form>
        </el-dialog>
    </basic-container>
</template>

<script>
    import {getList, getDetail, add, update, remove} from "@/api/bussinessmng/productratestrategy";
    import {mapGetters} from "vuex";

    export default {
        data() {
            return {
                form: {},
                query: {},
                loading: true,
                page: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                formVisible: false,
                selectionList: [],
                isView: false,
                option: {
                    height: 'auto',
                    calcHeight: 30,
                    tip: false,
                    searchShow: true,
                    searchMenuSpan: 6,
                    border: true,
                    index: true,
                    selection: true,
                    addBtn: false,
                    editBtn: false,
                    viewBtn: false,
                    dialogClickModal: false,
                    column: [
                        {
                            label: "策略名称",
                            prop: "name",
                            rules: [{
                                required: true,
                                message: "请输入策略名称",
                                trigger: "blur"
                            }]
                        },
                        {
                            label: "产品费率json字符串",
                            prop: "productRateJson",
                            rules: [{
                                required: true,
                                message: "请输入产品费率json字符串",
                                trigger: "blur"
                            }],
                            display: false
                        },
                        {
                            label: "付款场景",
                            prop: "paymentScene",
                            dicUrl: "/api/blade-system/dict-biz/dictionary?code=yee_payment_scene",
                            props:{
                                label: "dictValue",
                                value: "dictKey"
                            },
                        },
                    ]
                },
                data: [],
                formObj: {
                    id:null,
                    name: null,
                    rateList: []
                },
                formOption: {
                    column: [
                        {
                            label: "策略名称",
                            prop: "name",
                            rules: [{
                                required: true,
                                message: "请输入策略名称",
                                trigger: "blur"
                            }]
                        },
                        {
                            label: "付款场景",
                            prop: "paymentScene",
                            type: "select",
                            dicUrl: "/api/blade-system/dict-biz/dictionary?code=yee_payment_scene",
                            props:{
                                label: "dictValue",
                                value: "dictKey"
                            },
                            rules: [{
                                required: false,
                                message: "请选择付款场景",
                                trigger: "blur"
                            }]
                        },
                        {
                            label: '产品列表',
                            prop: 'rateList',
                            type: 'dynamic',
                            span: 24,
                            children: {
                                align: 'center',
                                headerAlign: 'center',
                                rowAdd:(done)=>{
                                    done({
                                        rateType:'SINGLE_PERCENT'
                                    });
                                },
                                column: [
                                    {
                                        label: '产品',
                                        type: "select",
                                        prop: "productCode",
                                        dicUrl: "/api/blade-system/dict-biz/dictionary?code=yee_product_rate",
                                        props:{
                                            label: "dictValue",
                                            value: "dictKey"
                                        },
                                        display: false,
                                        rules: [{
                                            required: true,
                                            message: '请选择产品',
                                        }],
                                    },
                                    {
                                        label: '计费策略',
                                        prop: "rateType",
                                        type: 'select',
                                        rules: [{
                                            required: true,
                                            message: '请选择计费策略',
                                            trigger: "blur"
                                        }],
                                        dicData: [{
                                            label: '单笔百分比',
                                            value: "SINGLE_PERCENT"
                                        }, {
                                            label: '单笔固定值',
                                            value: "SINGLE_FIXED"
                                        }],
                                    },
                                    {
                                        label: '单笔百分比',
                                        prop: "percentRate",
                                        placeholder: "0-100，0.21表示千分2.1，最多保留2位小数",
                                        rules: [{
                                            required: false,
                                            message: '请填写单笔百分比',
                                        }],
                                    },
                                    {
                                        label: '单笔固定值',
                                        prop: "fixedRate",
                                        placeholder: "整数位最多6位，小数位最多保留2位",
                                        rules: [{
                                            required: false,
                                            message: '请填写单笔固定值',
                                        }],
                                    }
                                ]
                            }
                        },
                    ]
                },
            };
        },
        computed: {
            ...mapGetters(["permission"]),
            permissionList() {
                return {
                    addBtn: this.vaildData(this.permission.productratestrategy_add, false),
                    viewBtn: this.vaildData(this.permission.productratestrategy_view, false),
                    delBtn: this.vaildData(this.permission.productratestrategy_delete, false),
                    editBtn: this.vaildData(this.permission.productratestrategy_edit, false)
                };
            },
            ids() {
                let ids = [];
                this.selectionList.forEach(ele => {
                    ids.push(ele.id);
                });
                return ids.join(",");
            }
        },
        methods: {
        closeDialog(){
            this.formObj = {id:null, name: null, rateList: []};
        },
          rateTypeChange(value, index){
              let percentRateCol = this.findObject(this.formOption.column[1].children.column, "percentRate");
              let fixedRateCol = this.findObject(this.formOption.column[1].children.column, "fixedRate");
              if (value === "SINGLE_PERCENT"){
                  percentRateCol.rules[0].required = true;
                  fixedRateCol.rules[0].required = false;
                  this.formObj.rateList[index].fixedRate = null;
              }else{
                  percentRateCol.rules[0].required = false;
                  fixedRateCol.rules[0].required = true;
                  this.formObj.rateList[index].percentRate = null;
              }
          },
          showAdd() {
              this.formObj = {id:null, name: null, rateList: []};
              this.formVisible = true;
              this.$forceUpdate();
          },
          handleEdit(row) {
              getDetail(row.id).then(res =>{
                  this.formObj = res.data.data;
                  this.formVisible = true;
              })
          },
            handleView(row) {
                getDetail(row.id).then(res =>{
                    this.formObj = res.data.data;
                    this.formVisible = true;
                })
            },
          rowSave(row, done, loading) {
              add(row).then(() => {
                  this.onLoad(this.page);
                  this.$message({
                      type: "success",
                      message: "操作成功!"
                  });
                  done();
              }, error => {
                  loading();
                  window.console.log(error);
              });
          },
          rowUpdate(row, index, done, loading) {
              update(row).then(() => {
                  this.onLoad(this.page);
                  this.$message({
                      type: "success",
                      message: "操作成功!"
                  });
                  done();
              }, error => {
                  loading();
                  console.log(error);
              });
          },
          rowDel(row) {
              this.$confirm("确定将选择数据删除?", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning"
              })
                  .then(() => {
                      return remove(row.id);
                  })
                  .then(() => {
                      this.onLoad(this.page);
                      this.$message({
                          type: "success",
                          message: "操作成功!"
                      });
                  });
          },
          handleDelete() {
              if (this.selectionList.length === 0) {
                  this.$message.warning("请选择至少一条数据");
                  return;
              }
              this.$confirm("确定将选择数据删除?", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning"
              })
                  .then(() => {
                      return remove(this.ids);
                  })
                  .then(() => {
                      this.onLoad(this.page);
                      this.$message({
                          type: "success",
                          message: "操作成功!"
                      });
                      this.$refs.crud.toggleSelection();
                  });
          },
          beforeOpen(done, type) {
              if (["edit", "view"].includes(type)) {
                  getDetail(this.form.id).then(res => {
                      this.form = res.data.data;
                  });
              }
              done();
          },
          searchReset() {
              this.query = {};
              this.onLoad(this.page);
          },
          searchChange(params, done) {
              this.query = params;
              this.page.currentPage = 1;
              this.onLoad(this.page, params);
              done();
          },
          selectionChange(list) {
              this.selectionList = list;
          },
          selectionClear() {
              this.selectionList = [];
              this.$refs.crud.toggleSelection();
          },
          currentChange(currentPage) {
              this.page.currentPage = currentPage;
          },
          sizeChange(pageSize) {
              this.page.pageSize = pageSize;
          },
          refreshChange() {
              this.onLoad(this.page, this.query);
          },
          onLoad(page, params = {}) {
              this.loading = true;
              getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
                  const data = res.data.data;
                  this.page.total = data.total;
                  this.data = data.records;
                  this.loading = false;
                  this.selectionClear();
              });
          },
          submit(data, done){
              let canSubmit = true;
              for(let index in data.rateList){
                  let item = data.rateList[index];
                  let rateType = item.rateType;
                  if(rateType === 'SINGLE_FIXED'){
                      this.formObj.rateList[item.$index].percentRate = null;
                      let fixedRate = item.fixedRate;
                      if(!fixedRate){
                          this.$message.error('第' + (item.$index + 1) + "行数据中单笔固定值必填");
                          canSubmit = false;
                          break;
                      }
                  }else{
                      this.formObj.rateList[item.$index].fixedRate = null;
                      let percentRate = item.percentRate;
                      if(!percentRate){
                          this.$message.error('第' + (item.$index + 1) + "行数据中单笔百分比必填");
                          canSubmit = false;
                          break;
                      }
                  }
              }
              if(canSubmit){
                  add(this.formObj).then(res =>{
                      this.onLoad(this.page, this.query);
                      this.formVisible = false;
                      done();
                  })
              }else{
                  done();
              }
          }
        }
    };
</script>

<style>
</style>
