<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="promoterName">
        <el-input
          placeholder="请输入达人名称"
          style="width: 240px"
          v-model="queryParams.promoterName"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="达人ID" prop="promoterId">
        <el-input
          placeholder="请输入达人ID"
          style="width: 240px"
          v-model="queryParams.promoterId"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="选择日期">
        <el-date-picker
          v-model="uploadDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </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-button
          type="primary"
          plain
          size="mini"
          @click="upload"
          style="margin-bottom: 15px"
        >导出
        </el-button
        >
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="typeList" ref="multipleTable">

      <el-table-column label="规则名称" align="center" prop="ruleName"></el-table-column>
      <el-table-column label="商品ID" align="center" prop="itemIds"></el-table-column>
      <el-table-column label="商品名称" align="center" prop="itemName"></el-table-column>
      <el-table-column label="达人ID" align="center" prop="promoterId"></el-table-column>
      <el-table-column label="达人名称" align="center" prop="promoterName"></el-table-column>
      <el-table-column label="单数" align="center" prop="orderNum"></el-table-column>
      <el-table-column label="有效单数" align="center" prop="validOrderNum"></el-table-column>
      <el-table-column label="上次结算有效单数" align="center" prop="lastSettlementOrderNum"></el-table-column>
      <el-table-column label="达人激励金额" align="center" prop="anchorAmount"></el-table-column>
      <el-table-column label="推荐人激励金额" align="center" prop="referenceAmount"></el-table-column>
      <el-table-column label="结算状态" align="center" prop="settlementStatusDesc"></el-table-column>


      <!--   <el-table-column label="达人ID" align="center" prop="promoterId">
           <template slot-scope="scope">
             <a style="text-align: center" @click="toDetail(scope.row)"
               >{{ scope.row.promoterId }}
             </a>
           </template>
         </el-table-column>
         <el-table-column label="达人名称" align="center" prop="promoterName">
           <template slot-scope="scope">
             <a style="text-align: center" @click="toDetail(scope.row)"
               >{{ scope.row.promoterName }}
             </a>
           </template>
         </el-table-column>-->


      <el-table-column label="操作" align="center" prop="action">
        <template slot-scope="scope">
          <el-button size="mini" type="text" :disabled="scope.row.settlementStatus!=2"  @click="removeRule(scope.row)"
          >结算
          </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"
            @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"
                @click="formBroadcast.ruleDetails.splice(index, 1)"
              >删除
              </el-button
              >
              <el-button
                type="error"
                plain
                size="mini"
                @click="addOrEdit(item, index)"
                v-if="!!ids"
              >确定
              </el-button
              >
            </div>

            <el-form-item
              label="序号"
              prop="sortCount"
              style="width: 100%"
              class="entire-line"
            >
              {{ index + 1 }}
            </el-form-item>
            <el-form-item
              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"
              >
              </el-input>
            </el-form-item>
            <el-form-item
              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"
              >
              </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="请输入主播奖励金额"
              ></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="请输入推荐人奖励金额"
              ></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 = {};
          "
        >取 消
        </el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {refreshCache} from "@/api/system/dict/type";
  import {downFilePost} from "@/api/supplyChain/supplyChain";
  import {
    getSettlementList,
    updatePromoterStatus,
    addRule,
    editRule,
    removeRule,
    editStatus,
    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,
          promoterId: undefined,
          promoterName: undefined,
        },
        uploadDate: new Date(),
        //页面所有的下拉数据
        queryParamsList: {},
        // 表单参数
        form: {},
        formBroadcast: {
          ruleDetails: [],
        },
        //上传报表下拉数据
        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;

      let start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
      let date = new Date(start);
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let dd = date.getDate();
      dd = dd < 10 ? "0" + dd : dd;
      this.uploadDate = `${y}-${MM}-${dd}`;

      this.getList();
    },
    filters: {},
    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);
        });
      },
      toDetail(item) {
        this.$router.replace({
          path: "/goodsManagement/settlementDetails",
          query: {
            statDate: this.uploadDate,
            promoterId: item.promoterId,
          },
        });
      },

      removeRule(item) {
        this.$modal
          .confirm(`请确认是否结算此数据？`)
          .then(() => {
            var params = {};
            params.id = +item.id;
            params.settlementStatus = 3;
            editStatus(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 = [];
        getSettlementList({statDate: this.uploadDate, ...this.queryParams})
          .then((response) => {
            this.loading = false;
            this.typeList = response.rows;
            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 = [];
        let start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
        let date = new Date(start);
        let y = date.getFullYear();
        let MM = date.getMonth() + 1;
        MM = MM < 10 ? "0" + MM : MM;
        let dd = date.getDate();
        dd = dd < 10 ? "0" + dd : dd;
        this.uploadDate = `${y}-${MM}-${dd}`;
        this.resetForm("queryForm");
        this.handleQuery();
      },
      upload() {
        downFilePost("/settlement/exportSettlementList", {
          statDate: this.uploadDate,
          ...this.queryParams,
        }).then((res) => {
          let blob = new Blob([res], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          });
          let downloadElement = document.createElement("a");
          let href = window.URL.createObjectURL(blob); //创建下载的链接
          downloadElement.href = href;
          downloadElement.download = "激励结算.xlsx"; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放掉blob对象
        });
      },
      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", []);
      },
      /** 编辑地址 新增达人*/
      handleAddbroadcast(item) {
        this.ids = item.id;
        this.edit = true;
        this.openAllocation = true;
        this.$set(this.formBroadcast, "consignee", item.consignee);
        this.$set(this.formBroadcast, "phone", item.phone);
        this.$set(this.formBroadcast, "promoterAddress", item.promoterAddress);
        this.$set(this.formBroadcast, "ruleName", item.ruleName);
        this.$set(this.formBroadcast, "promoterId", item.promoterId);
      },
      /** 修改按钮操作 */
      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>
