<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item label="月份:" prop="skuNo">
        <el-date-picker
          v-model="queryParams.configMonth"
          type="month"
          value-format="yyyyMM"
          placeholder="请选择月份" />
      </el-form-item>
      <el-form-item label="部门:" prop="deptCodes">
        <el-select
          v-model="queryParams.deptCodes"
          filterable
          placeholder="请选择部门"
          clearable
          multiple
        >
          <el-option
            v-for="(dict, index) in deptList"
            :key="index"
            :label="dict.deptName"
            :value="dict.deptCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌:" prop="brandCodes">
        <el-select
          v-model="queryParams.brandCodes"
          filterable
          placeholder="请选择品牌"
          clearable
          multiple
        >
          <el-option
            v-for="(dict, index) in brandNameList"
            :key="index"
            :label="dict.brandName"
            :value="dict.brandCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="渠道:" prop="channelCodes">
        <el-select
          v-model="queryParams.channelCodes"
          filterable
          placeholder="请选择渠道"
          clearable
          multiple
        >
          <el-option
            v-for="dict in channelList"
            :key="dict.channelCode"
            :label="dict.channelName"
            :value="dict.channelCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="品类:" prop="categoryCodes">
        <el-select
          v-model="queryParams.categoryCodes"
          filterable
          placeholder="请选择品类"
          clearable
          multiple
        >
          <el-option
            v-for="dict in categoryList"
            :key="dict.categoryCode"
            :label="dict.categoryName"
            :value="dict.categoryCode"
          />
        </el-select>
      </el-form-item>
      <el-row :gutter="10" class="mb8" type="flex" justify="end">
        <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-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
        <el-button
          type="success"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          >导入</el-button
        >
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport2"
          >下载渠道主数据</el-button
        >
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport3"
          >下载品牌主数据</el-button
        >
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport4"
          >下载品类主数据</el-button
        >
        <el-button type="primary" plain size="mini" @click="handleAdd"
          >日志</el-button
        >
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="proTable" 
    :height="tableHeight" border 
    :summary-method="getSummaries"
    show-summary
    v-loading="loading" :data="postList">
      <el-table-column label="月份" min-width="90" align="center" prop="configMonth" />
      <el-table-column label="部门" min-width="110" align="center" prop="deptName" />
      <el-table-column label="渠道" min-width="200" align="center" prop="channelName" />
      <el-table-column label="品牌" min-width="160" align="center" prop="brandName" />
      <el-table-column label="品类" min-width="160" align="center" prop="cateName" />
      <el-table-column label="月度销量目标" min-width="120" align="center" prop="goodNum">
        <template slot-scope="scope">
          <span>{{ $numFormat(scope.row.goodNum) }} </span>
        </template>
      </el-table-column>
      <el-table-column label="月度销售额目标" min-width="120" align="center" prop="saleTarget">
        <template slot-scope="scope">
          <span>{{ $numFormat(scope.row.saleTarget) }}</span> 
        </template>
      </el-table-column>
      <el-table-column label="月度毛利率目标" min-width="120" align="center" prop="grossProfitRate">
        <template slot-scope="scope">
          <span>{{ scope.row.grossProfitRate }}%</span>
        </template>
      </el-table-column>
      <el-table-column label="月度毛利目标" min-width="120" align="center" prop="grossProfit">
        <template slot-scope="scope">
          <span>{{ $numFormat(scope.row.grossProfit) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" min-width="100" align="center" prop="createdBy" />
      <el-table-column label="创建时间" min-width="180" align="center" prop="createdTime" />
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      class="fixed-pagination"
    />

    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="导入文件日志"
      bottom="100px"
      :visible.sync="open"
      width="800px"
      append-to-body
    >
      <el-table
        ref="historyLogTable"
        border
        :data="historyLogTableList"
      >
        <el-table-column label="文件" min-width="180" align="left" prop="filePath">
          <template slot-scope="scope">
            <a class="document-link" target="_blank" :href="'https://newfirst.oss-cn-shanghai.aliyuncs.com/' +scope.row.filePath" title="查看">
              {{ scope.row.fileName }}<i class="el-icon-link" />
            </a>
          </template>
        </el-table-column>
        <el-table-column label="上传人" min-width="180" align="left" prop="createBy" />
        <el-table-column
          label="上传时间"
          min-width="180"
          align="left"
          prop="createTime"
        />
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import{
  saleTargetList,
  saleTargetBrandList,
  saleTargetChannelList,
  saleTargetLogs,
  getCategoryList
} from "@/api/saleConfig/saleTarget";
import{
  gyDeptList
} from "@/api/saleConfig/index";
import { getToken } from "@/utils/auth";
import LoadMoreSelect from "@/components/LoadMoreSelect/index";

export default {
  name: "GoodsWarehouse",
  components: {
    LoadMoreSelect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      spuList: [],
      historyLogTableList: [],
      open: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API_NEW + "/sale/target/upload",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        "brandCodes": [],
        "channelCodes": [],
        "configMonth": "",
        "deptCodes": [],
        categoryCodes: []
      },
      bindForm: {
        bindSkuNo: "",
      },
      formSkuNo: '',
      platformList: [],
      brandNameList: [],
      channelList: [],
      // 表单参数
      form: { 
        platformName: "",
        platformSkuNo: "",
        skuNo: ""
      },
      tableHeight: 'auto',
      saveLoading: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近三天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近半个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      deptList: [],
      totalData: {},
      categoryList: []
    };
  },
  watch:{
    showSearch(n,_){
      this.$nextTick(() => {
        const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 210;
        this.tableHeight = height+'px';
      });
    }
  },
  created() {
    const currentMonthFirstDay = new Date();

    const year = currentMonthFirstDay.getFullYear();
    const month =
      currentMonthFirstDay.getMonth() + 1 < 10
        ? "0" + (currentMonthFirstDay.getMonth() + 1)
        : currentMonthFirstDay.getMonth() + 1;
    this.queryParams.configMonth = year  + month;

    this.relationPlatformList();
    this.getList();
  },
  mounted() {},
  methods: {
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
          return;
        }
        if(index == 5){
          sums[index] = this.$numFormat(this.totalData.totalGoodNum);
          return;
        }
        if(index==6){
          sums[index] = this.$numFormat(this.totalData.totalSaleTarget);
          return;
        }
        if(index==7){
          sums[index] = this.totalData.totalGrossProfitRate + '%';
          return;
        }
        if(index==8){
          sums[index] = this.$numFormat(this.totalData.totalGrossProfit);
          return;
        }
      });
      console.log(sums)
      return sums;
    },
    relationPlatformList(){
      saleTargetBrandList().then((res) => {
        this.brandNameList = res.data;
      });
      gyDeptList({}).then((res) => {
        this.deptList = res.data;
      });
      saleTargetChannelList().then((res) => {
        this.channelList = res.data || [];
      });
      getCategoryList().then((res) => {
        this.categoryList = res.data || [];
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
    
      saleTargetList(this.queryParams).then((response) => {
        if(response.status==200){
          this.totalData = response.data;
          this.postList = response.data.saleTargetListResDTOS;
          this.total = response.data.total;
          this.loading = false;
        }
        this.$nextTick(() => {
          const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 210;
          this.tableHeight = height+'px';
        });
      }).catch(err=>{
        this.postList = [];
        this.total = 0;
        this.loading = false;
        this.$nextTick(() => {
          const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 210;
          this.tableHeight = height+'px';
        });
      });
    },
    // 表单重置
    reset() {
      this.resetForm("queryForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      saleTargetLogs().then(res=>{
        if(res.status==200){
          this.historyLogTableList = res.data;
          this.open = true;
        }
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导出按钮操作 */
    handleExport() {
      const data = { ...this.queryParams };
      delete data.pageNum;
      delete data.pageSize;
      this.newDownload(
        "/sale/target/export",
        data,
        `销售目标_${new Date().getTime()}.xlsx`
      );
    },
    handleExport2() {
      this.newDownload(
        "/sale/target/export/channel",
        {},
        `渠道主数据_${new Date().getTime()}.xlsx`
      );
    },
    handleExport3() {
      this.newDownload(
        "/sale/target/export/brand",
        {},
        `品牌主数据_${new Date().getTime()}.xlsx`
      );
    },
    handleExport4() {
      this.newDownload(
        "/sale/target/export/category",
        {},
        `品类主数据_${new Date().getTime()}.xlsx`
      );
    },
    /** 下载模板操作 */
    importTemplate() {
      // this.newDownload(
      //   "spu/importTemplate",
      //   {},
      //   `spu_template_${new Date().getTime()}.xlsx`
      // );
      window.location.href = 'https://newfirst.oss-cn-shanghai.aliyuncs.com/saleTarget/temp/%E9%94%80%E5%94%AE%E7%9B%AE%E6%A0%87%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx';
    },
  },
};
</script>
<style scoped>
.charts-box {
  height: 350px;
  margin-top: 30px;
}
.erpPrice > span {
  color: #409eff;
}
.iconEdit {
  cursor: pointer;
}
.app-container {
  padding-bottom: 50px;
}
.document-link{
  color: #409eff;
  text-decoration: underline;
}
</style>
