<template>
  <div class="m-container">
    <div class="m-core">
      <div @click="chargeOperation('create')" v-permission="'sysConfig/update'" class="newBand">添加</div>
      <div @click="sporadicStatus = true" v-permission="'sysConfig/update'" 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" prop="money" label="金额(元)"></el-table-column>
          <el-table-column align="center" width="250px" label="操作">
            <template slot-scope="scope">
              <el-button v-if="permission('sysConfig/update')" @click="chargeOperation('update', scope.row)" type="text">修改</el-button>
              <el-button v-if="permission('sysConfig/update')" @click="chargeDel(scope.row)" 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="500px"
    >
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="所属分部" prop="organId" :label-width="formLabelWidth">
          <el-select v-model.trim="form.organId">
            <el-option
              v-for="item in branchList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="金额(元)" prop="money" :label-width="formLabelWidth">
          <el-input-number
            style="width: 100%;"
            v-model="form.money"
            :precision="0"
            controls-position="right"
            :min="1"
            :max="999999999"
          ></el-input-number>
        </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>

    <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 branchList2"
              :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="maxReceipt" :label-width="formLabelWidth2">
          <el-input-number
            style="width: 100%;"
            v-model="formSporadic.maxReceipt"
            :precision="0"
            controls-position="right"
            :min="1"
            :max="999999999"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="是否承担手续费" prop="feeFlag" :label-width="formLabelWidth2">
          <el-select v-model.trim="formSporadic.feeFlag" placeholder="请选择是否承担手续费">
            <el-option value="Y" label="是"></el-option>
            <el-option value="N" label="否"></el-option>
          </el-select>
        </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 { permission } from "@/utils/directivePage";
export default {
  name: "chargeProfitManager",
  components: { pagination },
  data() {
    return {
      tableList: [],
      pageInfo: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50] // 选择限制显示条数
      },
      chargeStatus: false,
      roleList: [], // 角色列表
      branchList: [], // 分部列表
      branchList2: [], // 分部列表
      formActionTitle: "create",
      formLabelWidth: "100px",
      formTitle: {
        create: "添加收费",
        update: "修改收费"
      },
      form: {
        organName: null,
        organId: null,
        money: null
      },
      rules: {
        organId: [
          { required: true, message: "请选择所属分部", trigger: "change" }
        ],
        money: [{ required: true, message: "请输入金额", trigger: "blur" }]
      },
      selectId: null, // 编号
      selectItem: {}, // 选中对象
      sporadicStatus: false, // {"organId":"2","maxReceipt":"75000","feeFlag":"Y"}
      formLabelWidth2: "120px",
      sporadicId: null, // 零星收费编号
      formSporadic: {
        organId: null,
        maxReceipt: 0,
        feeFlag: null
      },
      rulesSporadic: {
        organId: [
          { required: true, message: "请选择所属分部", trigger: "change" }
        ],
        maxReceipt: [
          { required: true, message: "请输入最大收款", trigger: "blur" }
        ],
        feeFlag: [
          { required: true, message: "请选择是否承担手续费", trigger: "change" }
        ]
      }
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    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;
        }
      });
    },
    onChargeSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let value = {};
          let str = "更新";
          let form = this.form;
          const money = form.money;
          const organId = form.organId;
          let status = false;
          if (this.formActionTitle == "create") {
            value[money] = organId;
            str = "添加";
            this.tableList.forEach(item => {
              value[item.money] = item.organId;
              if (item.money == money) {
                this.$message.error("输入金额不能重复");
                status = true;
              }
            });
          } else if (this.formActionTitle == "update") {
            const selectItem = this.selectItem;
            selectItem.organId = form.organId;
            selectItem.money = form.money;
            this.tableList.forEach(item => {
              value[item.money] = item.organId;
              if (item.money == money && item.key != selectItem.key) {
                this.$message.error("输入金额不能重复");
                status = true;
              }
            });
          }
          if (status) {
            return;
          }
          let params = {
            id: this.selectId,
            paranValue: JSON.stringify(value),
            paramName: "amount_channel"
          };
          sysConfigUpdate(params).then(res => {
            if (res.code == 200) {
              this.messageTips(str, 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 branchQueryPage({
        // 获取分部
        delFlag: 0,
        rows: 9999
      }).then(res => {
        this.branchList = [];
        this.branchList2 = [];
        if (res.code == 200 && res.data && res.data.rows) {
          res.data.rows.forEach(item => {
            this.branchList.push({
              label: item.name,
              value: item.id
            });
            this.branchList2.push({
              label: item.name,
              value: item.id
            });
          });
        }
      });
      await sysConfigList({ group: "payment_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 (item.paramName === "sporadic_channel") {
              this.formSporadic = item.paranValue
                ? JSON.parse(item.paranValue)
                : { organId: null, maxReceipt: 0, feeFlag: null };
              this.sporadicId = item.id;
            }
          });
          this.branchList.forEach(item => {
            for (let key in paranValue) {
              if (paranValue[key] == item.value) {
                tempResult.push({
                  organId: item.value,
                  organName: item.label,
                  money: key,
                  key: +new Date() + item.value
                });
              }
            }
          });
          this.tableList = tempResult;
        }
      });
    },
    chargeOperation(type, data) {
      this.formActionTitle = type;
      this.chargeStatus = true;
      this.branchList.forEach(item => {
        this.tableList.forEach(table => {
          if (item.value == table.organId) {
            item.disabled = true;
          }
        });
      });
      // 修改的时候
      if (type == "update") {
        this.form = {
          organId: data.organId,
          organName: data.organName,
          money: data.money,
          key: data.key
        };
        this.selectItem = data;
      } else if (type == "create") {
      }
    },
    chargeDel(row) {
      // 删除数据
      this.$confirm("你确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let value = {};
          this.tableList.forEach(item => {
            if (row.organId != item.organId) {
              value[item.money] = item.organId;
            }
          });
          let params = {
            id: this.selectId,
            paranValue: JSON.stringify(value),
            paramName: "amount_channel"
          };
          sysConfigUpdate(params).then(res => {
            if (res.code == 200) {
              this.messageTips("删除", res);
            }
          });
        })
        .catch();
    },
    onFormClose(formName) {
      this.form = {
        organName: null,
        organId: null,
        money: null
      };
      // 关闭弹窗重置验证
      this.$refs[formName].resetFields();
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 0 20px;
}
::v-deep .el-select,
::v-deep .el-date-editor.el-input {
  width: 100% !important;
}
::v-deep .el-input-number.is-controls-right .el-input__inner {
  text-align: left;
}
.newBand {
  display: inline-block;
}
</style>