<template>
  <div class="m-container">
    <div class="m-core">
      <div @click="chargeOperation('create')" v-permission="'paymentConfig/add'" class="newBand">添加</div>
      <!-- 列表 -->
      <div class="tableWrap">
        <el-table :data="tableList" :header-cell-style="{background:'#EDEEF0',color:'#444'}">
          <el-table-column align="center" prop="organName" label="分部"></el-table-column>
          <el-table-column align="center" label="收款方式">
            <template slot-scope="scope">{{ scope.row.payType | paymentChannelStatus }}</template>
          </el-table-column>
          <el-table-column align="center" prop="hfMerNo" label="汇付商户号"></el-table-column>
          <el-table-column align="center" prop="yqMerNo" label="双乾商户号"></el-table-column>
          <el-table-column align="center" label="收款比例">
            <template slot-scope="scope">
              {{ scope.row.type == 1 ? '笔数比例' : null }}
              {{ scope.row.type == 2 ? '金额比例' : null }}
            </template>
          </el-table-column>
          <el-table-column align="center" width="250px" label="操作">
            <template slot-scope="scope">
              <el-button
                @click="chargeOperation('update', scope.row)"
                v-permission="'paymentConfig/update'"
                type="text"
              >修改</el-button>
              <!-- <el-button
                @click="chargeDel(scope.row)"
                v-permission="'paymentConfig/del'"
                type="text"
              >删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <pagination
          :total="pageInfo.total"
          :page.sync="pageInfo.page"
          :limit.sync="pageInfo.limit"
          :page-sizes="pageInfo.page_size"
          @pagination="getList"
        />
      </div>
    </div>

    <el-dialog
      :title="formTitle[formActionTitle]"
      :visible.sync="chargeStatus"
      @close="onFormClose('ruleForm')"
      width="700px"
    >
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="所属分部" prop="organId" :label-width="formLabelWidth">
          <el-select v-model.trim="form.organId" placeholder="请选择所属分部">
            <el-option
              v-for="(item, index) in branchList"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收款方式" prop="payType" :label-width="formLabelWidth">
          <el-select v-model.trim="form.payType" @change="onPayTypeChange" placeholder="请选择收款方式">
            <el-option value="YQPAY" label="双乾"></el-option>
            <el-option value="ADAPAY" label="汇付"></el-option>
          </el-select>
        </el-form-item>
        <!-- prop="yqMerNo" :error="result.yqError" -->
        <el-form-item
          label="双乾商户号"
          :required="form.payType === 'YQPAY'"
          :label-width="formLabelWidth"
        >
          <el-input
            type="text"
            @blur="onMerNoBlur('YQPAY')"
            placeholder="请输入双乾商户号"
            v-model.trim="form.yqMerNo"
          ></el-input>
        </el-form-item>
        <!--  prop="hfMerNo" :error="result.hfError" -->
        <el-form-item
          label="汇付商户号"
          :required="form.payType === 'ADAPAY'"
          :label-width="formLabelWidth"
        >
          <el-input
            type="text"
            @blur="onMerNoBlur('ADAPAY')"
            placeholder="请输入汇付商户号"
            v-model.trim="form.hfMerNo"
          ></el-input>
        </el-form-item>
        <el-form-item label="收费比例" required :label-width="formLabelWidth">
          <el-radio
            v-model.trim.number="form.type"
            @change="onRadioChange('ruleForm')"
            :label="2"
          >金额比例</el-radio>
          <el-radio
            v-model.trim.number="form.type"
            @change="onRadioChange('ruleForm')"
            :label="1"
          >笔数比例</el-radio>
        </el-form-item>

        <el-form-item class="moreRule" :label-width="formLabelWidth" style="margin-bottom: 0;">
          <span class="min">分部</span>
          <span class="min">比例</span>
          <span class="max">是否承担手续费</span>
        </el-form-item>
        <div class="moreRule">
          <div class="moreRuleIn" v-for="(domain, index) in result.domains" :key="domain.key">
            <el-form-item class="setWidth" :label="'第' + (index + 1)" :label-width="formLabelWidth">
              <!-- @change="onBranchChange" -->
              <el-select
                v-model.trim="domain.organId"
                placeholder="请选择分部"
                clearable
              >
                <el-option
                  v-for="(item, index) in calcBranchList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="setWidth">
              <el-input
                type="number"
                v-number
                min="0"
                clearable
                :max="form.type === 1 ? 10 : 100"
                placeholder="请输入比例"
                @mousewheel.native.prevent
                v-model.trim="domain.scale"
              >
                <template v-if="form.type === 2" slot="append">%</template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model.trim="domain.feeFlag"
                placeholder="请选择是否承担手续费"
                style="width: 150px !important;"
                clearable
              >
                <el-option value="Y" label="是"></el-option>
                <el-option value="N" label="否"></el-option>
              </el-select>
              <el-button
                v-if="index != 0"
                @click.prevent="removeDomain(result, domain)"
              >删除</el-button>
            </el-form-item>
          </div>
          <div class="el-form-item__error" v-if="result.errorText">{{ result.errorText }}</div>
        </div>
        <el-form-item class="add" :label-width="formLabelWidth">
          <el-button icon="el-icon-plus" @click="addDomain(result)">新增</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="chargeStatus = false">取 消</el-button>
        <el-button @click="onChargeSubmit('ruleForm')" type="primary">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import pagination from "@/components/Pagination/index";
import {
  paymentConfigQueryPage,
  paymentConfigAdd,
  paymentConfigUpdate,
  paymentConfigDel
} from "@/api/systemManage";
import { getPaymentConfigs } from "./api";
import { branchQueryPage } from "@/api/specialSetting";
import store from "@/store";
export default {
  name: "chargeProfitManager",
  components: { pagination },
  data() {
    return {
      tableList: [],
      pageInfo: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50] // 选择限制显示条数
      },
      chargeStatus: false,
      branchList: [], // 分部列表
      calcBranchList: [], // 可选比例分部
      formActionTitle: "create",
      formLabelWidth: "100px",
      formTitle: {
        create: "添加收费比例",
        update: "修改收费比例"
      },
      form: {
        organId: null,
        hfMerNo: null,
        yqMerNo: null,
        payType: null, // 支付渠道
        type: 2,
        routeScale: []
      },
      rules: {
        hfMerNo: [
          { required: true, message: "请输入汇付商户号", trigger: "blur" }
        ],
        yqMerNo: [
          { required: true, message: "请输入双乾商户号", trigger: "blur" }
        ],
        organId: [
          { required: true, message: "请选择所属分部", trigger: "change" }
        ],
        payType: [
          { required: true, message: "请选择收款方式", trigger: "change" }
        ]
      },
      result: {
        domains: [
          {
            organId: null,
            scale: null,
            feeFlag: null,
            disabled: false,
            key: Date.now()
          }
        ],
        errorText: null,
        yqError: null,
        hfError: null
      }
    };
  },
  mounted() {
    this.getList();
    this.getRoleList();
  },
  methods: {
    async onPayTypeChange(val) {
      if (!val) {
        return;
      }
      this.calcBranchList = [];
      this.result.domains = [
        {
          organId: null,
          scale: null,
          feeFlag: null,
          disabled: false,
          key: Date.now()
        }
      ];
      this.result.errorText = null;
      await getPaymentConfigs({ payType: val }).then(res => {
        if (res.code == 200 && res.data) {
          res.data.forEach(item => {
            this.calcBranchList.push({
              label: item.organName,
              value: item.organId
            });
          });
        }
      });
    },
    onRadioChange(formName) {
      this.$refs[formName].clearValidate();
    },
    onMerNoBlur(type) {
      let form = this.form;
      let result = this.result;
      if (type === "YQPAY" && form.payType === "YQPAY") {
        if (form.yqMerNo) {
          result.yqError = null;
        } else {
          result.yqError = "请输入双乾商户号";
        }
      } else if (type === "ADAPAY" && form.payType === "ADAPAY") {
        if (form.hfMerNo) {
          result.hfError = null;
        } else {
          result.hfError = "请输入汇付商户号";
        }
      }
    },
    onChargeSubmit(formName) {
      this.$refs[formName].validate(valid => {
        let params = JSON.parse(JSON.stringify(this.form));
        let result = this.result;
        params.routeScale = null;
        // if (params.payType === "YQPAY" && !params.yqMerNo) {
        //   result.yqError = "请输入双乾商户号";
        //   return;
        // } else if (params.payType === "ADAPAY" && !params.hfMerNo) {
        //   result.hfError = "请输入汇付商户号";
        //   return;
        // }
        this.addDomain(result, true);
        if (valid && !result.errorText) {
          let tempResult = [];
          result.domains.forEach(item => {
            if (item.organId) {
              tempResult.push({
                organId: item.organId,
                scale: item.scale,
                feeFlag: item.feeFlag
              });
            }
          });
          params.routeScale =
            tempResult.length > 0 ? JSON.stringify(tempResult) : null;
          if (params.payType === "YQPAY" && !params.yqMerNo && !params.routeScale) {
            // result.yqError = "请输入双乾商户号";
            this.$message.error('请输入双乾商户号或比例')
            return;
          } else if (params.payType === "ADAPAY" && !params.hfMerNo && !params.routeScale) {
            // result.hfError = "请输入汇付商户号";
            this.$message.error('请输入汇付商户号或比例')
            return;
          }

          if (this.formActionTitle == "create") {
            if (params.id) {
              // 判断有没有Id，如果有则删除
              delete params.id;
            }
            paymentConfigAdd(params).then(res => {
              this.messageTips("添加", res);
            });
          } else if (this.formActionTitle == "update") {
            paymentConfigUpdate(params).then(res => {
              this.messageTips("修改", res);
            });
          }
        } else {
          return;
        }
      });
    },
    messageTips(title, res) {
      if (res.code == 200) {
        this.$message.success(title + "成功");
        this.chargeStatus = false;
        this.getList();
      } else {
        this.$message.error(res.msg);
      }
    },
    // onBranchChange(val) {
    //   this.calcBranchList.forEach(item => {
    //     if (val == item.value) {
    //       item.disabled = true;
    //     } else {
    //       item.disabled = false;
    //     }
    //   });
    // },
    addDomain(form, checked) {
      let domains = form.domains,
        forms = this.form,
        singleLength = domains.length,
        lastDate = domains[singleLength - 1]; // 获取倒数一个对象

      // 如果三个值都为空，则不用检验
      if (!lastDate.organId && !lastDate.scale && !lastDate.feeFlag && checked) {
        form.errorText = ''
        return;
      }

      let countScale = 0;
      let selectFeeCount = 0,
          selectFeeCount2 = 0
      domains.forEach(item => {
        countScale += Number(item.scale);
        if(forms.type == 2) {
          if(item.feeFlag == 'Y') {
            selectFeeCount++
          }
        } else if(forms.type == 1) {
          if(item.feeFlag == 'N') {
            selectFeeCount2++
          }
        }
      });
      if(selectFeeCount > 1) {
        form.errorText = `承担手续费只能设置一次“是”`;
        return
      } else if(selectFeeCount2 > 0) {
        form.errorText = `承担手续费只能设置“是”`;
        return
      }
      let num = 0;
      if (forms.type === 2) {
        num = 100;
      } else if (forms.type === 1) {
        num = 10;
      }

      if (!lastDate.organId) {
        form.errorText = "选择分部不能为空";
        return;
      }

      if (!parseInt(lastDate.scale)) {
        form.errorText = "比例不能为空";
        return;
      } else if (parseInt(lastDate.scale) > num) {
        form.errorText = "比例不能超过" + num;
        return;
      } else if (parseInt(countScale) > num) {
        form.errorText = "比例总和应为" + num;
        return;
      }

      if (!lastDate.feeFlag) {
        form.errorText = "请选择是否承担手续费";
        return;
      }

      form.errorText = null;
      if (!checked) {
        lastDate.disabled = true;
        domains.push({
          organId: null,
          scale: null,
          feeFlag: null,
          disabled: false,
          key: Date.now()
        });
      } else {
        if (parseInt(countScale) != num) {
          form.errorText = "比例总和应为" + num;
          return;
        }
        if(forms.type == 2) {
          if(selectFeeCount != 1) {
            form.errorText = "承担手续费必须设置一次“是”"
            return;
          }
        }
      }
    },
    removeDomain(form, item) {
      // this.calcBranchList.forEach(organ => {
      //   if (item.organId == organ.value) {
      //     console.log(true)
      //     organ.disabled = false;
      //   }
      // });
      var index = form.domains.indexOf(item);
      if (index !== -1) {
        form.domains.splice(index, 1);
        // 取消最后一个数据的禁用状态
        form.domains[form.domains.length - 1].disabled = false;
        form.errorText = null;
      }
    },
    getList() {
      let params = {};
      params.rows = this.pageInfo.limit;
      params.page = this.pageInfo.page;
      paymentConfigQueryPage(params).then(res => {
        if (res.code == 200 && res.data) {
          this.tableList = res.data.rows;
          this.pageInfo.total = res.data.total;
        }
      });
    },
    getRoleList() {
      //
      branchQueryPage({
        // 获取分部
        delFlag: 0,
        rows: 9999
      }).then(res => {
        if (res.code == 200 && res.data && res.data.rows) {
          res.data.rows.forEach(item => {
            this.branchList.push({
              label: item.name,
              value: item.id
            });
          });
        }
      });
    },
    chargeOperation(type, data) {
      this.formActionTitle = type;
      this.chargeStatus = true;
      // 修改的时候
      if (type == "update") {
        this.onPayTypeChange(data.payType);
        this.form = {
          id: data.id,
          type: Number(data.type),
          hfMerNo: data.hfMerNo,
          yqMerNo: data.yqMerNo,
          payType: data.payType,
          organId: data.organId
        };
        if (data.routeScale) {
          this.result.domains = [];
          let scaleJson = JSON.parse(data.routeScale);
          let scaleLength = scaleJson.length;
          scaleJson.forEach((item, index) => {
            let temp = {};
            if (scaleLength == index + 1) {
              temp.disabled = false;
            } else {
              temp.disabled = true;
            }
            temp.organId = item.organId;
            temp.scale = item.scale;
            temp.feeFlag = item.feeFlag;
            this.result.domains.push(temp);
          });
        }
      }
    },
    chargeDel(row) {
      // 删除数据
      // paymentConfigDel
      this.$confirm("你确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          paymentConfigDel({ id: row.id }).then(res => {
            this.messageTips("删除", res);
          });
        })
        .catch();
    },
    onFormClose(formName) {
      // 关闭弹窗重置验证
      this.form = {
        organId: null,
        hfMerNo: null,
        yqMerNo: null,
        payType: null, // 支付渠道
        type: 2,
        routeScale: []
      };
      this.result = {
        domains: [
          {
            organId: null,
            scale: null,
            feeFlag: null,
            disabled: false,
            key: Date.now()
          }
        ],
        errorText: null,
        yqError: null,
        hfError: null
      }
      this.$refs[formName].resetFields();
    }
  }
};
</script>
<style lang="scss" scoped>
/deep/.el-button--primary {
  background: #14928a;
  border-color: #14928a;
  color: #fff;
  &:hover,
  &:active,
  &:focus {
    background: #14928a;
    border-color: #14928a;
    color: #fff;
  }
}
/deep/.el-dialog__body {
  padding: 0 20px;
}
/deep/.el-select,
/deep/.el-date-editor.el-input {
  width: 100% !important;
}

.moreRule {
  background: #f0f0f0;
  position: relative;

  .el-form-item__error {
    color: #f56c6c;
    font-size: 12px;
    line-height: 1;
    position: absolute;
    left: 100px;
    top: 100%;
    margin-top: -21px;
  }
}
.add {
  margin-bottom: 22px;
  background: #f0f0f0;
  padding-bottom: 22px;
}
.moreRuleIn {
  .el-form-item {
    display: inline-block;
    &:first-child {
      /deep/.el-form-item__content {
        margin-left: 100px !important;
      }
    }
    /deep/.el-form-item__content {
      margin-left: 0 !important;
    }
  }

  .setWidth {
    /deep/.el-form-item__content {
      width: 150px;
    }
  }
  /deep/.el-input-group__append {
    padding: 0 8px;
  }
}
.min,
.max {
  display: inline-block;
  width: 150px;
  text-align: center;
}
</style>