<template>
  <div class="m-container">
    <div class="m-core">
      <div @click="sporadicStatus = true" v-permission="'sysConfig/update'" class="newBand">零星收费设置</div>
      <p style="color: red; display: inline-block; padding-left: 10px">金额设置0则不做限制</p>

      <!-- 列表 -->
      <el-form :model="result" ref="ruleFormValid">
        <el-form-item class="moreRule" :label-width="formLabelWidth" style="margin-bottom: 0;">
          <span class="min">分部</span>
          <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="index">
            <el-form-item class="setWidth"
              :label-width="formLabelWidth"
              :label="'第' + (index + 1)"
              :prop="'domains.' + index + '.organId'"
              :rules="{
                required: true, message: '请选择所属分部', trigger: 'change'
              }">
              <el-select v-model.trim="domain.organId" clearable :disabled="domain.disabled" placeholder="请选择所属分部">
                <el-option
                  v-for="(item, index1) in selects.branchs"
                  :key="index1"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="setWidth" :prop="'domains.' + index + '.routeOrganId'" :rules="[
              { required: true, message: '请选择收款分部', trigger: 'change' },
            ]">
              <el-select clearable v-model.trim="domain.routeOrganId" :disabled="domain.disabled" placeholder="请选择收款分部">
                <el-option
                  v-for="(item, index) in calcBranchList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="setWidth" :prop="'domains.' + index + '.amount'" :rules="validAmount">
              <el-input
                type="age"
                clearable
                placeholder="请输入比例"
                :disabled="domain.disabled"
                @mousewheel.native.prevent
                v-model.number="domain.amount"
              >
              </el-input>
            </el-form-item>
            <el-form-item :prop="'domains.' + index + '.type'" :rules="[
              { required: true, message: '请选择购买类型', trigger: 'change' },
            ]">
              <el-select
                clearable
                v-model.trim="domain.type"
                placeholder="购买类型"
                style="width: 180px !important"
                :disabled="domain.disabled"
              >
                <el-option value="vipBuy" label="VIP课"></el-option>
                <el-option value="practiceBuy" label="网管课"></el-option>
                <el-option value="musicGroupBuy" label="乐团课"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                v-if="index != 0 && !domain.disabled"
                @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">
          <el-button icon="el-icon-plus" @click="addDomain(result)">新增</el-button>
        </el-form-item>
      </el-form>
      <el-button style="margin-left: 100px" @click="onSaveDomain" type="primary">保 存</el-button>
    </div>

    <el-dialog title="零星收费设置" :visible.sync="sporadicStatus" width="500px">
      <el-form :model="formSporadic" :rules="rulesSporadic" ref="ruleFormSporadic">
        <el-form-item label="收款分部" prop="organId" :label-width="formLabelWidth2">
          <el-select v-model.trim="formSporadic.organId">
            <el-option
              v-for="item in calcBranchList"
              :key="item.value"
              :label="item.label"
              :value="item.value.toString()"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="金额(元)" prop="minReceipt" :label-width="formLabelWidth2">
          <el-input
            style="width: 100%;"
            @mousewheel.native.prevent
            v-model.number="formSporadic.minReceipt"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="sporadicStatus = false">取 消</el-button>
        <el-button @click="onSporadicSubmit('ruleFormSporadic')" type="primary">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import pagination from "@/components/Pagination/index";
import { branchQueryPage } from "@/api/specialSetting";
import { sysConfigList, sysConfigUpdate } from "@/api/generalSettings";
import store from "@/store";
import { getPaymentConfigs } from "./api";
import { permission } from "@/utils/directivePage";
let validAmount = (rule, value, callback) => {
  if (value != 0 && typeof value === 'string') {
    callback(new Error("请输入金额"));
  } else if (value < 0) {
    callback(new Error("输入金额必须大于或等于0"));
  } else if (value > 999999999) {
    callback(new Error("输入金额必须小于999999999"));
  } else {
    callback();
  }
};
export default {
  name: "chargeProfitManager",
  components: { pagination },
  data() {
    return {
      tableList: [],
      pageInfo: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50] // 选择限制显示条数
      },
      roleList: [], // 角色列表
      calcBranchList: [],
      formLabelWidth: "100px",
      result: {
        domains: [
          {
            organId: null,
            routeOrganId: null,
            amount: null,
            type: null
          }
        ],
        // errorText: null,
      },
      validAmount: [
        { required: true, validator: validAmount, trigger: 'blur' },
        { type: 'number', message: '金额必须为数字值' }],
      selectId: null, // 编号
      selectItem: {}, // 选中对象
      sporadicStatus: false, // {"organId":"2","minReceipt":"75000"}
      formLabelWidth2: "120px",
      sporadicId: null, // 零星收费编号
      formSporadic: {
        organId: null,
        minReceipt: null
      },
      rulesSporadic: {
        organId: [
          { required: true, message: "请选择所属分部", trigger: "change" }
        ],
        minReceipt: [
        { required: true, validator: validAmount, trigger: 'blur' },
        { type: 'number', message: '金额必须为数字值' }],
      }
    };
  },
  mounted() {
    this.__init()
    this.getList();
  },
  methods: {
    async __init() {
      this.$store.dispatch('setBranchs')
      await getPaymentConfigs().then(res => {
        if (res.code == 200 && res.data) {
          res.data.forEach(item => {
            this.calcBranchList.push({
              label: item.organName,
              value: item.organId
            });
          });
        }
      });
    },
    permission (str) {
      return permission(str)
    },
    onSporadicSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let params = {
            id: this.sporadicId,
            paranValue: JSON.stringify(this.formSporadic),
            paramName: "sporadic_channel"
          };
          sysConfigUpdate(params).then(res => {
            if (res.code == 200) {
              this.messageTips("保存", res);
            }
          });
        } else {
          return;
        }
      });
    },
    messageTips(title, res) {
      if (res.code == 200) {
        this.$message.success(title + "成功");
        this.chargeStatus = false;
        this.sporadicStatus = false;
        this.getList();
      } else {
        this.$message.error(res.msg);
      }
    },
    async getList() {
      await sysConfigList({ group: "channel_config" }).then(res => {
        if (res.code == 200 && res.data.length > 0) {
          let tempResult = [];
          let paranValue = {};
          res.data.forEach((item, index) => {
            if (item.paramName === "amount_channel") {
              paranValue = item.paranValue ? JSON.parse(item.paranValue) : [];
              this.selectId = item.id;
              if(paranValue.length > 0) {
                this.result.domains = []
                paranValue.forEach((item, index) => {
                  this.result.domains.push({
                    organId: item.organId,
                    routeOrganId: item.routeOrganId,
                    amount: item.amount,
                    type: item.type
                  })
                })
              }
            }
            if (item.paramName === "sporadic_channel") {
              this.formSporadic = item.paranValue
                ? JSON.parse(item.paranValue)
                : { organId: null, minReceipt: null };
              this.sporadicId = item.id;
            }
          });
        }
      });
    },
    onSaveDomain() { // 保存设置
      this.$refs["ruleFormValid"].validate(valid => {
        if(valid) {
          const domain = this.result.domains
          let params = {
            id: this.selectId,
            paranValue: JSON.stringify(domain),
            paramName: "amount_channel"
          };
          sysConfigUpdate(params).then(res => {
            if (res.code == 200) {
              this.messageTips("保存", res);
            }
          });
        } else {
          return
        }
      })
    },
    addDomain(form, checked) {
      let domains = form.domains,
        forms = this.form,
        singleLength = domains.length,
        lastDate = domains[singleLength - 1]; // 获取倒数一个对象
      this.$refs["ruleFormValid"].validate(valid => {
        if(valid) {
          if (!checked) {
            // lastDate.disabled = true;
            domains.push({
              organId: null,
              routeOrganId: null,
              amount: null,
              type: null
            });
          }
        } else {
          return
        }
      })
    },
    removeDomain(form, item) {
      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;
      }
    },
  }
};
</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;
}
/deep/.el-input-number.is-controls-right .el-input__inner {
  text-align: left;
}
.newBand {
  display: inline-block;
}


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

  .el-form-item__error {
    color: #f56c6c;
    font-size: 12px;
    line-height: 1;
    position: absolute;
    left: 120px;
    top: 100%;
    margin-top: -21px;
  }
}
.add {
  margin-bottom: 22px;
  background: #f8f8f8;
  padding-bottom: 22px;
  padding-left: 100px;
}
.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: 180px;
    }
  }
  /deep/.el-input-group__append {
    padding: 0 8px;
  }
}
.min,
.max {
  display: inline-block;
  width: 180px;
  text-align: center;
}
</style>