<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="商品名称" align="center" prop="itemName"></el-table-column>
      <el-table-column label="商品ID" align="center" prop="itemIds"></el-table-column>
      <el-table-column label="招商" align="center" prop="itemUserName"></el-table-column>
      <el-table-column label="达人名称" align="center" prop="promoterName"></el-table-column>
      <el-table-column label="达人ID" align="center" prop="promoterId"></el-table-column>
      <el-table-column label="渠道" align="center" prop="promoterUserName"></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,100]"
    />

  </div>
</template>

<script>

  import {
    listType,
    getType,
    delType,
    addType,
    updateType,
    refreshCache,
  } from "@/api/system/dict/type";
  import {downFilePost} from "@/api/supplyChain/supplyChain";
  import {
    getSettlementList,
    addRule,
    editRule,
    editStatus
  } from "@/api/goodsManagement/goods";

  export default {
    name: "Settlement",
    dicts: ["sys_normal_disable"],
    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: {
        },
        // 分配销售展示列表
        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();
    },

    mounted() {
      this.$nextTick(() => {
        this.getList();
      });
    },

    filters: {},
    methods: {

      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>
