<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="是否结算" prop="categoryId">
        <el-select
          filterable
          v-model="queryParams.status"
          placeholder="选择媒体"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in queryParamsList.statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="达人名称" prop="promoterName">
        <el-input
          style="width: 240px"
          v-model="queryParams.promoterName"
          placeholder="请输入达人名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="达人ID" prop="promoterId" v-if="showPromoterSech">
        <el-input
          style="width: 240px"
          v-model="queryParams.promoterId"
          placeholder="请输入达人ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="itemTitle">
        <el-input
          style="width: 240px"
          v-model="queryParams.itemTitle"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品id" prop="itemId" v-if="showItemSech">
        <el-input
          style="width: 240px"
          v-model="queryParams.itemId"
          placeholder="请输入商品id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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"
          type="daterange"
          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
          icon="el-icon-plus"
          size="mini"
          @click="toAdd()"
        >新增激励
        </el-button>

        <el-button
          type="primary"
          plain
          icon="el-icon-document-add"
          size="mini"
          @click="importData"
        >导入大佬激励
        </el-button>

        <el-button
          type="primary"
          plain
          size="mini"
          @click="downloadTem"
        >下载模版
        </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="infoList" @selection-change="handleSelectionChange"
              :row-style="TableRowStyle"
    >

      <!--      <el-table-column
              label="结算类型"
              align="center"
              prop="activityItemStatus" width="100px"
            >
              <template slot-scope="scope">
                <div v-if="!!scope.row.promoterType">
                  {{ scope.row.promoterType | promoterTypeName }}
                </div>
                <div v-else>-</div>
              </template>
            </el-table-column>-->
      <el-table-column label="渠道" align="center" prop="promoterCreateName"/>
      <el-table-column label="招商" align="center" prop="itemCreateName"/>
      <el-table-column label="日期" align="center" prop="statDate" width="100px"/>
      <el-table-column label="达人名称" align="center" prop="promoterName" width="120px">
        <template slot-scope="scope">
          <div style="display: flex; width: 100%">
            <div style="width: 100%" class="item-name-calss">
              <a
                style="
                      text-overflow: ellipsis;
                      white-space: nowrap;
                      overflow: hidden;
                      width: 100%;
                    "
                :title="scope.row.promoterName"
              >
                {{ scope.row.promoterName }}
              </a>

            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="达人ID" align="center" prop="promoterId" width="100px"/>

      <el-table-column label="商品名称" align="center" prop="itemTitle" width="280px">
        <template slot-scope="scope">
          <div style="display: flex; width: 100%">
            <div style="width: 100%" class="item-name-calss">
              <a
                style="
                      text-overflow: ellipsis;
                      white-space: nowrap;
                      overflow: hidden;
                      width: 100%;
                    "
                :title="scope.row.itemTitle"
              >
                {{ scope.row.itemTitle }}
              </a>

            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品id" align="center" prop="itemId" width="140px"/>

      <el-table-column label="累计结算单量" align="center" prop="totalSettlementNum" width="100px"/>
      <el-table-column label="本次结算单量" align="center" prop="currentSettlementNum" width="100px"/>
      <el-table-column label="结算单价" align="center" prop="settlementPrice" width="100px"/>
      <el-table-column label="主播奖励金额" align="center" prop="anchorAmount" width="100px"/>
      <el-table-column label="推荐人奖励金额" align="center" prop="referenceAmount" width="120px"/>
      <el-table-column label="合计金额" align="center" prop="totalAmount" width="100px"/>
      <el-table-column width="200" label="备注" align="center" prop="remarks">
        <template slot-scope="scope">
          <el-input
            type="textarea"
            v-model="scope.row.remarks"
          >
          </el-input>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160px">

        <template slot-scope="scope">
          <el-button size="mini" :disabled="scope.row.status  == 2" type="text" @click="jiesuan(scope.row)">结算
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(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"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" :inline="true">
        <el-form-item label="日期:" prop="statDate" style="width: 100%">
          <el-date-picker
            style="width: 180px"
            v-model="uploadDate"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            range-separator="-"
            placeholder="请输入日期">

          </el-date-picker>
        </el-form-item>


        <el-form-item label="商品id:" prop="itemId">
          <el-input v-model="form.itemId" placeholder="请输入商品id"/>
        </el-form-item>
        <el-form-item label="达人ID:" prop="promoterId">
          <el-input v-model="form.promoterId" placeholder="请输入达人ID"/>
        </el-form-item>
        <el-form-item label="本次结算单量:" prop="currentSettlementNum">
          <el-input v-model="form.currentSettlementNum" placeholder="请输入本次结算单量="/>
        </el-form-item>
        <el-form-item label="累计单量:" prop="totalSettlementNum">
          <el-input v-model="form.totalSettlementNum" placeholder="请输入累计结算单量"/>
        </el-form-item>
        <el-form-item label="结算单价:" prop="settlementPrice">
          <el-input v-model="form.settlementPrice" placeholder="请输入结算单价"/>
        </el-form-item>
        <el-form-item label="主播金额:" prop="anchorAmount">
          <el-input v-model="form.anchorAmount" placeholder="请输入主播奖励金额"/>
        </el-form-item>
        <el-form-item label="推荐人金额:" prop="referenceAmount">
          <el-input v-model="form.referenceAmount" placeholder="请输入推荐人奖励金额"/>
        </el-form-item>
        <el-form-item label="累计金额:" prop="referenceAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入累计金额"/>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="importTitle" :visible.sync="importOpen" width="500px" append-to-body>

      <el-form ref="importForm" :model="form" :rules="rules" label-width="80px">
        <el-upload
          class="upload-demo"
          action="http://192.168.1.181:9003/isv/supply_chain/insertRewardBaseInfoByExcel"
          :before-upload="handleBeforeUpload"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          accept=""
          :on-exceed="handleExceed"
          :file-list="fileList"
          :show-file-list="false"
        >
          <el-button size="small" icon="el-icon-upload">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传.csv .xlsx .xls文件
            <br/>
            <span v-if="!!dateFile">{{ dateFile.name }}</span>
          </div>
        </el-upload>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFile" :loading="confirmLoading"
        >确 定
        </el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import {
  listInfo,
  getInfo,
  delInfo,
  addInfo,
  updateInfo,
  getTotal,
  importData,
  updateStatus
} from "@/api/goodsManagement/financeData";
import {downFilePost} from "@/api/supplyChain/supplyChain";


export default {
  name: "financeDataDetail",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      importTitle: null,
      title: null,
      showItemSech: true,
      showPromoterSech: true,
      confirmLoading: false,
      dateFile: null,
      fileList: [],
      importOpen: false,
      uploadDate: [new Date(), new Date()],
      userId: null,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      infoList: [],
      // 弹出层标题

      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemId: null,
        itemTitle: null,
        promoterId: null,
        promoterName: null,
        status: null,
        statDate: null
      },
      queryParamsList: {

        statusList: [
          {value: 1, label: "未结算"},
          {value: 2, label: "已结算"},
        ],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  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}`, `${y}-${MM}-${dd}`];
    this.getList();
    this.getListTotal();
  },

  filters: {
    promoterTypeName(type) {
      const statusMap = {
        1: "常规",
        2: "大佬"
      };
      return statusMap[type];
    },

  },
  methods: {

    upload() {
      if (this.$route.query.promoterId) {
        this.queryParams.promoterId = this.$route.query.promoterId
        this.uploadDate = []
      }

      if (this.$route.query.itemId) {
        this.queryParams.itemId = this.$route.query.itemId
        this.uploadDate = []
      }


      downFilePost("/finance/reward/exportDetail",
        this.addDateRange(
          this.queryParams,
          this.uploadDate,
          "startDate",
          "endDate"
        )
      ).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对象
      });
    },


    getListTotal() {
      if (this.$route.query.promoterId) {
        this.queryParams.promoterId = this.$route.query.promoterId
        this.uploadDate = []
      }

      if (this.$route.query.itemId) {
        this.queryParams.itemId = this.$route.query.itemId
        this.uploadDate = []
      }
      getTotal(
        this.addDateRange(
          {
            ...this.queryParams
          },
          this.uploadDate,
          "startDate",
          "endDate"
        )
      ).then((res) => {
        this.itemSummary = [res].map((item) => {
          return {
            ...item,
            itemTitle: "总计",
            userName: "总计"
          };
        });
      });
    },

    jiesuan(item) {
      this.$modal
        .confirm(`请确认是否结算此数据？`)
        .then(() => {
          var params = {};
          params.id = item.id;
          updateStatus(params)
            .then((res) => {
              this.getList();
              this.$modal.msgSuccess("结算成功");
            })
            .catch(() => {
            });
        })
        .catch(() => {
        });
    },

    TableRowStyle({row, rowIndex}) {
      // 注意，这里返回的是一个对象
      let rowBackground = {};
      if (row.status == 2) {
        rowBackground.background = "lightBlue";
      } else {
        rowBackground.background = "";
      }
      return rowBackground;
    },

    submitFile() {
      console.log(this.dateFile)
      this.$refs["importForm"].validate((valid) => {
        if (valid) {
          if (this.dateFile) {
            this.confirmLoading = true;
            let formData = new FormData();
            formData.append("file", this.dateFile);
            importData(formData)
              .then((res) => {
                this.confirmLoading = false;
                this.$message.success("上传成功");
                this.cancel();
                this.handleQuery();
              })
              .catch((err) => {
                this.confirmLoading = false;
              });
          } else {
            this.$message.error("请上传文件");
          }
        }
      });
    },


    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },

    beforeRemove(file, fileList) {
      return false;
    },

    /** 删除文件 */
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },

    /** 上传文件 */
    handlePreview(file) {
      console.log(file);
    },
    /** 上传文件前验证 */
    handleBeforeUpload(file) {
      console.log(file);
      const fileSuffix = ["xlsx", "xls", "csv"];
      const fileName = file.name;
      const fileStrArr = fileName.split(".");
      const suffix = fileStrArr[fileStrArr.length - 1];
      let result = fileSuffix.some((item) => {
        return item === suffix;
      });

      if (!result) {
        this.$message.error("不支持该文件类型");
        this.loadDisabled = false;
        return false;
      }
      this.dateFile = file;
      return false;
    },

    importData() {
      this.reset();
      this.importOpen = true;
      this.importTitle = "导入激励";
    },

    downloadTem() {
      window.location.href = `https://live-1301855440.cos.ap-chongqing.myqcloud.com/excle/%E5%A4%A7%E4%BD%AC%E7%BB%93%E7%AE%97%E6%A8%A1%E6%9D%BF.xlsx`
    },

    toAdd(item) {
      let query = {};
      if (this.$route.query.promoterId) {
        query.promoterId = this.$route.query.promoterId
      }
      if (this.$route.query.itemId) {
        query.itemId = this.$route.query.itemId
      }
      this.$router.replace({
        path: "/goodsManagement/addFinanceData",
        query: query
      });
    },


    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      if (this.$route.query.promoterId) {
        this.queryParams.promoterId = this.$route.query.promoterId
        this.uploadDate = []
      }

      if (this.$route.query.itemId) {
        this.queryParams.itemId = this.$route.query.itemId
        this.uploadDate = []
      }
      listInfo(
        this.addDateRange(
          {
            ...this.queryParams
          },
          this.uploadDate,
          "startDate",
          "endDate"
        )).then(response => {
        this.infoList = this.itemSummary.concat(response.rows);
        this.total = response.total;
        this.loading = false;
      }).catch((err) => {
        this.loading = false;
      });

    },

    getUploadDate() {
      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}`, `${y}-${MM}-${dd}`];
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.importOpen = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        itemId: null,
        itemTitle: null,
        promoterId: null,
        promoterName: null,
        itemCreateId: null,
        itemCreateName: null,
        promoterCreateId: null,
        promoterCreateName: null,
        statDate: null,
        currentSettlementNum: null,
        totalSettlementNum: null,
        settlementPrice: null,
        anchorAmount: null,
        referenceAmount: null,
        totalAmount: null,
        remarks: null,
        createTime: null,
        updateTime: null
      };
      this.dateFile = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.getListTotal();
    },
    /** 重置按钮操作 */
    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}`, `${y}-${MM}-${dd}`];
      this.queryParams.status = null;
      console.log(this.routeItemId)
      this.resetForm("queryForm");
      this.handleQuery();

    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增激励";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInfo(id).then(response => {
        this.form = response.data;
        this.uploadDate = response.data.statDate;
        this.open = true;
        this.title = "修改激励";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.statDate = this.uploadDate;
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getUploadDate();
              this.getList();
            });
          } else {
            this.form.statDate = this.uploadDate;
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getUploadDate();
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除所选的数据项？').then(function () {
        return delInfo(ids);
      }).then(() => {
        this.getList();
        this.getUploadDate();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    }
  }
}
;

</script>
