<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="规则名称" prop="ruleName">
        <el-input
          placeholder="请输入规则名称"
          style="width: 240px"
          v-model="queryParams.ruleName"
        >
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @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="el-icon-document-add"
          size="mini"
          @click="addNew"
          >新增规则
        </el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="typeList" ref="multipleTable">
      <el-table-column label="规则名称" align="center" prop="ruleName" width="300">
        <template slot-scope="scope">
          <div v-if="!!scope.row.ruleName">
            <span v-if="!scope.row.promoterPhoneEdit">{{ scope.row.ruleName }}</span>
            <el-input
              v-else
              v-model="scope.row.ruleName"
              placeholder="请输入规则名称"
              style="width: 200px"
            ></el-input>
            <a
              :class="!scope.row.promoterPhoneEdit ? 'el-icon-edit' : 'el-icon-check'"
              @click="editRuleName(scope.row)"
              style="color: deepskyblue; margin-left: 10px; display: inline"
            ></a>
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="规则类型" align="center" prop="ruleType">
        <template slot-scope="scope">
          <div v-if="!!scope.row.ruleType">
            {{ scope.row.ruleType  | ruleTypeName }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="userName"> </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <div v-if="!!scope.row.createTime">
            {{ scope.row.createTime.split("T").join(" ") }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" prop="action">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="lookDetail(scope.row)"
            >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="removeRule(scope.row)"
            :disabled="scope.row.id == '1'"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      :pageSizes="[10, 20, 30, 50]"
    />

    <!-- 添加直播 -->
    <el-dialog
      :title="!!ids ? '修改规则' : '新增规则'"
      :visible.sync="openAllocation"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="formBroadcast"
        :model="formBroadcast"
        :rules="rulesBroadcast"
        label-width="150px"
        :inline="true"
      >
        <span
          style="
            color: red;
            display: inline-block;
            width: 100%;
            text-align: center;
            font-size: 18px;
          "
        >
          新增完成后，子规则不可删除</span
        >

        <el-form-item label="创建人" prop="userName" style="width: 100%">
          {{ $store.getters.name }}
        </el-form-item>
        <el-form-item
          label="规则名称"
          prop="ruleName"
          style="width: 100%"
          class="entire-line"
        >
          <el-input
            placeholder="请输入规则名称"
            style="width: 240px"
            :disabled="!!ids"
            v-model="formBroadcast.ruleName"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="规则类型"
          prop="ruleType"
          style="width: 100%"
          class="entire-line"
        >
          <el-select
            filterable
            :disabled="!!ids"
            v-model="formBroadcast.ruleType"
            placeholder="请选择规则类型"
            clearable
            style="width: 240px"
          >
            <el-option label="按区间结算" value="1"> </el-option>
            <el-option label="按单数结算" value="2"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label=" " style="width: 100%" class="entire-line">
          <el-button
            type="primary"
            plain
            icon="el-icon-document-add"
            size="mini"
            :disabled="ids == '1'"
            @click="
              formBroadcast.ruleDetails.push({
                startItemCount: undefined,
                endItemCount: undefined,
                anchorAmount: undefined,
                referenceAmount: undefined,
              })
            "
            >子规则新增
          </el-button>
        </el-form-item>
        <div
          style="
            height: 300px;
            overflow-y: auto;
            width: 100%;
            overflow-x: hidden;
            border: 2px solid #f2f2f2;
            padding-top: 10px;
          "
          v-if="formBroadcast.ruleDetails.length > 0"
        >
          <div
            v-for="(item, index) in formBroadcast.ruleDetails"
            :key="index"
            style="position: relative"
          >
            <div style="position: absolute; right: 25px">
              <el-button
                type="error"
                plain
                icon="el-icon-close"
                size="mini"
                v-if="!item.id"
                :disabled="ids == '1'"
                @click="formBroadcast.ruleDetails.splice(index, 1)"
                >删除</el-button
              >
              <el-button
                type="error"
                plain
                size="mini"
                @click="addOrEdit(item, index)"
                v-if="!!ids"
                :disabled="ids == '1'"
                >确定</el-button
              >
            </div>

            <el-form-item
              label="序号"
              prop="sortCount"
              style="width: 100%"
              class="entire-line"
            >
              {{ index + 1 }}
            </el-form-item>
            <el-form-item
              v-if="formBroadcast.ruleType == '1'"
              label="起始单数"
              style="width: 100%"
              class="entire-line"
              :prop="'ruleDetails.' + index + '.startItemCount'"
              :rules="{
                required: true,
                message: '起始单数不能为空',
                trigger: 'blur',
              }"
            >
              <el-input
                placeholder="请输入起始单数"
                style="width: 240px"
                v-model.number="item.startItemCount"
                :disabled="ids == '1'"
              >
              </el-input>
            </el-form-item>

            <el-form-item
              v-if="formBroadcast.ruleType == '2' || formBroadcast.ruleType == '3'"
              label="结算单数"
              style="width: 100%"
              class="entire-line"
              :prop="'ruleDetails.' + index + '.startItemCount'"
              :rules="{
                required: true,
                message: '起始单数不能为空',
                trigger: 'blur',
              }"
            >
              <el-input
                placeholder="请输入结算单数"
                style="width: 240px"
                v-model.number="item.startItemCount"
                :disabled="ids == '1'"
              >
              </el-input>
            </el-form-item>
            <el-form-item
              v-if="formBroadcast.ruleType == '1'"
              label="结束单数"
              :prop="'ruleDetails.' + index + '.endItemCount'"
              :rules="{
                required: true,
                message: '结束单数不能为空',
                trigger: 'blur',
              }"
              style="width: 100%"
              class="entire-line"
            >
              <el-input
                placeholder="请输入结束单数"
                style="width: 240px"

                v-model.number="item.endItemCount"
                :disabled="ids == '1'"
              >
              </el-input>
            </el-form-item>
            <el-form-item
              label="主播奖励金额"
              :prop="'ruleDetails.' + index + '.anchorAmount'"
              :rules="{
                required: true,
                message: '主播奖励金额不能为空',
                trigger: 'blur',
              }"
              style="width: 100%"
              class="entire-line"
            >
              <el-input-number
                style="width: 240px"
                v-model="item.anchorAmount"
                :precision="2"
                :step="0.1"
                :min="0"
                placeholder="请输入主播奖励金额"
                :disabled="ids == '1'"
              ></el-input-number>
            </el-form-item>
            <el-form-item
              label="推荐人奖励金额"
              prop="referenceAmount"
              style="width: 100%"
              class="entire-line"
            >
              <el-input-number
                style="width: 240px"
                v-model="item.referenceAmount"
                :precision="2"
                :step="0.1"
                :min="0"
                placeholder="请输入推荐人奖励金额"
                :disabled="ids == '1'"
              ></el-input-number>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!ids">
        <el-button type="primary" @click="submitFormBroadcast" :loading="confirmLoading"
          >确 定</el-button
        >
        <el-button
          @click="
            confirmLoading = false;
            openAllocation = false;
            formBroadcast = { ruleDetails: [], ruleType: '1' };
          "
          >取 消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { refreshCache } from "@/api/system/dict/type";
import { getPromoterList, addPromoter, editPromoter } from "@/api/promoter/promoter";
import {
  getRuleList,
  getAllRuleList,
  addRule,
  editRule,
  removeRule,
  getRuleDetailByRuleId,
  editDetail,
  addDetail,
} from "@/api/goodsManagement/goods";
export default {
  name: "Rule-Config",
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: null,
      okIds: null,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      typeList: [],
      //上传文件类型
      fileType: [".doc", ".xls", ".xlsx", ".ppt", ".pdf", ".csv"],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openFp: false,
      formFp: {},
      // 是否可编辑
      edit: false,
      // 分配销售
      openAllocation: false,
      // 选择的销售id
      saleId: undefined,
      // 销售列表
      saleList: [],
      // 分配销售确定loading
      confirmLoadingSale: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleName: undefined,
      },
      //页面所有的下拉数据
      queryParamsList: {},
      // 表单参数
      form: {},
      formBroadcast: {
        ruleDetails: [],
        ruleType: "1",
      },
      //上传报表下拉数据
      formList: {},
      fileList: [],
      accept: "",
      //获取销售线索文件流
      dateFile: new FormData(),
      //销售线索上传loading
      confirmLoading: false,
      // 表单校验
      rules: {},
      rulesBroadcast: {
        ruleName: {
          required: true,
          message: "规则名称必填",
          trigger: "blur",
        },
        ruleType: {
          required: true,
          message: "规则类型必选",
          trigger: "change",
        },
      },
      // 分配销售展示列表
      ksInfo: null,
      userId: null,
    };
  },
  created() {
    this.userId = this.$store.getters.userId;
    this.getList();
  },
  filters: {
    ruleTypeName(status) {
      const ruleMap = {
        1: "按区间结算",
        2: "按单量结算",
        3: "按达人结算",
      };
      return ruleMap[status];
    },


  },
  methods: {
    addOrEdit(item, index) {
      if (item.id) {
        console.log(item);
        editDetail({
          id: item.id,
          ruleId: this.ids,
          anchorAmount: item.anchorAmount,
          endItemCount: item.endItemCount,
          referenceAmount: item.referenceAmount,
          sortCount: item.sortCount,
          startItemCount: item.startItemCount,
        }).then((res) => {
          this.$message.success("修改成功");
        });
      } else {
        addDetail({
          ruleId: this.ids,
          anchorAmount: item.anchorAmount,
          endItemCount: item.endItemCount,
          referenceAmount: item.referenceAmount,
          sortCount: index,
          startItemCount: item.startItemCount,
        }).then((res) => {
          this.$message.success("添加成功");
        });
      }
    },
    lookDetail(item) {
      getRuleDetailByRuleId({ ruleId: item.id }).then((res) => {
        this.ids = item.id;
        this.edit = true;
        this.openAllocation = true;
        this.$set(this.formBroadcast, "ruleName", item.ruleName);
        this.$set(this.formBroadcast, "ruleType", "" + item.ruleType);
        this.$set(this.formBroadcast, "ruleDetails", res.data);
      });
    },
    removeRule(item) {
      this.$modal
        .confirm(`请确认是否删除该规则？`)
        .then(() => {
          var params = {};
          params.id = +item.id;
          removeRule(params)
            .then((res) => {
              this.getList();
              this.$modal.msgSuccess("删除成功");
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
    editRuleName(item) {
      if (!item.promoterPhoneEdit) {
        item.promoterPhoneEdit = !item.promoterPhoneEdit;
      } else {
        if (!!item.ruleName) {
          editRule({ ruleName: item.ruleName, id: item.id })
            .then((res) => {
              this.handleQuery();
            })
            .catch(() => {});
        } else {
          this.$message.error("规则名称不能不填");
        }
      }
    },
    /** 查询字典类型列表 */
    getList() {
      this.loading = true;
      this.typeList = [];
      getAllRuleList({ userId: this.userId, ...this.queryParams })
        .then((response) => {
          this.loading = false;
          this.typeList = response.rows.map((item) => {
            return {
              ...item,
              promoterPhoneEdit: false,
            };
          });
          this.total = response.total;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.confirmLoading = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.dateFile = null;
      this.resetForm("formBroadcast");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    addNew() {
      this.openAllocation = true;
      this.edit = false;
      this.ids = null;
      this.confirmLoading = false;
      this.formBroadcast = {};
      setTimeout(() => {
        this.$refs.formBroadcast.clearValidate();
      }, 0);
      this.$set(this.formBroadcast, "ruleDetails", []);
      this.$set(this.formBroadcast, "ruleType", "1");
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
    },
    /** 新增直播确定按钮 */
    submitFormBroadcast: function () {
      this.$refs["formBroadcast"].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          let formData = {
            userId: this.userId,
            userName: this.$store.getters.name,
            ...this.formBroadcast,
            ruleDetails: this.formBroadcast.ruleDetails.map((item, index) => {
              return {
                ...item,
                sortCount: index + 1,
              };
            }),
          };
          console.log(formData);
          if (!this.ids) {
            addRule(formData)
              .then((res) => {
                this.confirmLoading = false;
                this.$message.success("新增成功");
                this.openAllocation = false;
                this.ids = null;
                this.cancel();
                this.handleQuery();
              })
              .catch((err) => {
                this.confirmLoading = false;
              });
          } else {
            formData.id = this.ids;
            editRule(formData)
              .then((res) => {
                this.confirmLoading = false;
                this.$message.success("修改成功");
                this.openAllocation = false;
                this.ids = null;
                this.cancel();
                this.handleQuery();
              })
              .catch((err) => {
                this.confirmLoading = false;
              });
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.entire-line {
  width: 100%;
}

::v-deep .entire-line .el-form-item__content {
  width: 60%;
}

::v-deep .el-form-item__label {
  white-space: nowrap;
}
</style>
<style scoped lang="scss">
::v-deep a {
  color: #409eff;
  display: block;
  text-align: left;
}

.item-name-calss p {
  margin: 0;
  text-align: left;
}

.tableBox {
  width: 100%;
}
</style>
