<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="promoterName">
        <el-input
          v-model="queryParams.promoterName"
          placeholder="请输入达人名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="达人ID" prop="promoterId">
        <el-input
          v-model="queryParams.promoterId"
          placeholder="请输入达人ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="itemTitle">
        <el-input
          v-model="queryParams.itemTitle"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品id" prop="itemId">
        <el-input
          v-model="queryParams.itemId"
          placeholder="请输入商品id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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-plus"
          size="mini"
          @click="toAdd()"

        >新增
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <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-col>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">

      <el-table-column label="达人名称" align="center" prop="promoterName" width="140px">
        <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="180px">
        <template slot-scope="scope">
          <div style="display: flex; width: 100%">
            <div style="width: 100%">
              <a
                style="color: #00afff"
                :title="scope.row.promoterId"
              >
                {{ scope.row.promoterId }}
              </a>

            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="渠道" align="center" prop="promoterCreateName"/>
      <el-table-column label="商品名称" align="center" prop="itemTitle" width="280px" v-if="showItem">
        <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="promoterId" width="140px">
        <template slot-scope="scope">
          <div style="display: flex; width: 100%">
            <div style="width: 100%">
              <a
                style="color: #00afff"
                :title="scope.row.itemId"
              >
                {{ scope.row.itemId }}
              </a>

            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="招商" align="center" prop="itemCreateName" width="100px"/>
      <el-table-column label="最近结算日期" align="center" prop="maxDate" width="100px"/>
      <el-table-column label="累计结算单量" align="center" prop="totalSettlementNum"/>
    </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>
      <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,
  totalListInfo
} from "@/api/goodsManagement/financeData";


export default {
  name: "FinanceData",
  data() {
    return {
      confirmLoading: false,
      dateFile: null,
      fileList: [],
      importOpen: false,
      uploadDate: new Date(),
      userId: null,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      importTitle: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemId: null,
        itemTitle: null,
        promoterId: null,
        promoterName: null,
        statDate: null
      },
      // 表单参数
      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}`;

    this.getList();
  },
  methods: {
    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() {
      this.$router.replace({
        path: "/goodsManagement/addFinanceData",
      });
    },


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

    },

    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;
    },


    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      totalListInfo(this.queryParams).then(response => {
        this.infoList = 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}`;
    },


    // 取消按钮
    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();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.showItem = true;
      this.showPromoter = true;
      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>
