<template>
  <div class="app-container">
    <div>
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px" size="default" class="ry_form">
        <el-form-item label="编号" prop="code">
          <el-input v-model.trim="queryParams.code" placeholder="编号" clearable />
        </el-form-item>
        <el-form-item label="规则名称" prop="name">
          <el-input v-model.trim="queryParams.name" placeholder="请输入规则名称" clearable />
        </el-form-item>
        <el-form-item label="规则状态" prop="status">
          <el-select v-model="queryParams.status">
            <el-option v-for="item in userStatusMap" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="适用订单类型" prop="type">
          <el-select v-model="queryParams.type">
            <el-option v-for="item in userTypeMap" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item class="flex_one tr">
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="tableLoading" :data="userDataInfo.data" border empty-text="暂无数据">
        <el-table-column label="编号" prop="code" />
        <el-table-column label="规则名称" prop="name" />
        <el-table-column label="是否分配手续费" prop="divideFeeFlag">
          <template v-slot="scope"> ￥ {{ scope.row.fee || '0.00' }} </template>
        </el-table-column>

        <el-table-column label="手续费分配方式" prop="feeType">
          <template v-slot="scope"> ￥ {{ scope.row.actualMoney || '0.00' }} </template>
        </el-table-column>
        <el-table-column label="状态" prop="status">
          <template v-slot="scope">
            {{ getEmulistLabelById(scope.row.status, userStatusMap) }}
          </template>
        </el-table-column>
        <el-table-column label="创建部门" prop="createDept" width="100" />
        <el-table-column label="创建人" prop="createBy" width="100" />
        <el-table-column label="创建时间" prop="createTime" width="100" />
        <el-table-column label="操作" width="200">
          <template v-slot="scope">
            <el-button text type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改 </el-button>
            <el-button text type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="userDataInfo.total"
        :total="userDataInfo.total"
        v-model:page="dataParams.current"
        v-model:limit="dataParams.size"
        @pagination="getList"
      />
    </div>
    <!-- 添加或修改规则对话框 -->
    <el-dialog :title="title" v-model="open" width="900" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150" inline class="dialog-form-one">
        <el-row>
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入名称" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="编码" prop="code">
            <el-input v-model="form.code" placeholder="请输入编码" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="是否分配手续费">
            <DictRadio v-model="form.divideFeeFlag" :radioList="userYesOrNoMap" radioData="sys_common_yesno" /> </el-form-item
        ></el-row>
        <el-row></el-row>
        <el-row>
          <el-form-item label="手续费分配方式">
            <DictRadio v-model="form.feeType" :radioList="userDivideFeeMap" radioData="trans_divide_feetype" /> </el-form-item
        ></el-row>
        <el-row>
          <el-form-item label="状态"> <DictRadio v-model="form.status" :radioList="userStatusMap" radioData="sys_normal_disable" /> </el-form-item
        ></el-row>
        <el-row>
          <el-form-item label="适用订单类型">
            <DictRadio v-model="form.type" :radioList="userDivideRuleMap" radioData="trans_divide_order_type" /> </el-form-item
        ></el-row>

        <el-form-item label="规则详情">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" @click="handleRuleAdd">新增</el-button>
            </el-col>
          </el-row>
          <el-card v-show="divideRuleDetailList.length > 0">
            <el-row v-for="(item, index) in divideRuleDetailList">
              <el-col :span="2">
                <el-row>
                  <el-col>序号</el-col>
                  <el-col> {{ index + 1 }}</el-col>
                </el-row>
              </el-col>
              <el-col :span="7">
                <el-row>
                  <el-col>金额分配比例</el-col>
                  <el-col><el-input type="number" v-model="item.moneyPercent" placeholder="请输入编码" style="width: 150px" /></el-col>
                </el-row>
              </el-col>
              <el-col :span="7">
                <el-row>
                  <el-col>手续费分配比例</el-col>
                  <el-col><el-input type="number" v-model="item.feePercent" placeholder="请输入编码" style="width: 150px" /></el-col>
                </el-row>
              </el-col>
              <el-col :span="6">
                <el-row>
                  <el-col>账户类型</el-col>
                  <el-col>
                    <el-select v-model="item.type" clearable placeholder="请选择" style="width: 150px">
                      <el-option v-for="item in userDivideAccountMap" :key="item.value" :label="item.label" :value="Number(item.value)" />
                    </el-select>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="2">
                <el-row>
                  <el-col>操作</el-col>
                  <el-col>
                    <el-button text type="primary" icon="Delete" @click="handleItemDelete(index)"></el-button>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-card>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { getUserDivideRuleDetail, getUserDivideRuleList, editUserDivideRule, addUserDivideRule, deleteUserDivideRule } from '@/api/trade/index';

export default {
  name: 'DivideRuleManage',
  data() {
    return {
      userDataInfo: {
        total: 0,
        data: [],
        record: {}
      },
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        code: null,
        name: null,
        type: undefined,
        status: undefined,
        divideFeeFlag: undefined,
        feeType: undefined
      },

      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '规则名称不能为空', trigger: 'blur' }],
        divideFeeFlag: [{ required: true, message: '请选择是否分配手续费', trigger: 'change' }],
        status: [{ required: true, message: '请选择规则状态', trigger: 'change' }],
        type: [{ required: true, message: '请选择适用订单类型', trigger: 'change' }]
      },
      divideRuleDetailList: [],
      tableLoading: false,
      dataParams: {
        current: 1,
        size: 10
      },
      userYesOrNoMap: [],
      userDivideFeeMap: [],
      userDivideRuleMap: [],
      userStatusMap: [],
      userDivideAccountMap: []
    };
  },
  async created() {
    this.getList();
    await this.getPageEmu();
  },
  methods: {
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        type: undefined,
        status: undefined
      };
      this.divideRuleDetailList = [];
      this.resetForm('form');
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },

    handleRuleAdd() {
      this.divideRuleDetailList = [...this.divideRuleDetailList, ...[{}]];
    },

    handleItemDelete(index) {
      const newArr = [...this.divideRuleDetailList];
      newArr.splice(index, 1);
      this.divideRuleDetailList = newArr;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加分账规则';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getUserDivideRuleDetail(id).then((response) => {
        const { data } = response || {};
        if (data.divideFeeFlag != null) {
          data.divideFeeFlag = data.divideFeeFlag.toString();
        }
        if (data.feeType != null) {
          data.feeType = data.feeType.toString();
        }
        if (data.status != null) {
          data.status = data.status.toString();
        }
        if (data.type != null) {
          data.type = data.type.toString();
        }
        if (data.details) {
          this.divideRuleDetailList = data.details || [];
        }
        this.form = data || {};
        this.open = true;
        this.title = '修改分账规则';
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.divideRuleDetailList.length == 0) {
            return this.$modal.msgWarning('规则详情不能为空！');
          }
          const params = {
            ...this.form,
            details: this.divideRuleDetailList
          };
          if (this.form.id != null) {
            editUserDivideRule(params).then((response) => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addUserDivideRule(params).then((response) => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除规则编号为"' + ids + '"的数据项？')
        .then(function () {
          return deleteUserDivideRule(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
    /** 查询会员信息列表 */
    getList() {
      this.tableLoading = true;
      const { current: pageNum, size: pageSize } = this.queryParams;
      const query = { ...this.queryParams, pageNum: undefined, pageSize: undefined };
      const pageReq = { current: pageNum - 1, size: pageSize };
      getUserDivideRuleList(query, pageReq)
        .then((response) => {
          const { records = [], total = 0 } = response.data || {};
          this.userDataInfo = {
            total: total,
            data: records || []
          };
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },

    async getPageEmu() {
      const userYesOrNoMap = await this.getDictionaryByKey('sys_common_yesno');
      const userDivideFeeMap = await this.getDictionaryByKey('trans_divide_feetype');
      const userDivideRuleMap = await this.getDictionaryByKey('trans_divide_order_type');
      const userStatusMap = await this.getDictionaryByKey('sys_normal_disable');
      const userDivideAccountMap = await this.getDictionaryByKey('trans_divide_account_type');

      this.userYesOrNoMap = userYesOrNoMap;
      this.userDivideFeeMap = userDivideFeeMap;
      this.userDivideRuleMap = userDivideRuleMap;
      this.userStatusMap = userStatusMap;
      this.userDivideAccountMap = userDivideAccountMap;
    }
  }
};
</script>
