<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <el-form-item label="统计日期:" prop="queryDate">
        <el-date-picker
          v-model="queryParams.queryDate"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="选择日期"
          :clearable="false"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="品牌:" prop="brandCodes">
        <el-select
          v-model="queryParams.brandCodes"
          filterable
          placeholder="品牌"
          clearable
          multiple
          @change="brandChange"
        >
          <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="spuNos">
        <el-select
          v-model="queryParams.spuNos"
          multiple
          filterable
          placeholder="型号"
          clearable
        >
          <el-option
            v-for="(dict, index) in spuList"
            :key="index"
            :label="dict.spuName"
            :value="dict.spuNo"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="商品编码:" prop="skus">
        <el-input
          v-model="queryParams.skus"
          placeholder="多个商品编码使用逗号隔开"
          clearable
        />
      </el-form-item>
      <el-form-item label="商品名称:" prop="skuNo">
        <LoadMoreSelect
          :skuNo="queryParams.skuNo"
          @queryParams="(val) => (queryParams.skuNo = val)"
        />
      </el-form-item>
      <el-form-item label="仓库名称:" prop="skus">
        <el-select
          v-model="queryParams.warehouseNames"
          multiple
          placeholder="请选择仓库名称"
          clearable
        >
          <el-option
            v-for="dict in warehouseLists"
            :key="dict.warehouseName"
            :label="dict.warehouseName"
            :value="dict.warehouseName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标签:" prop="tags">
        <!-- multiple -->
        <el-select
          v-model="queryParams.tags"
          style="width: 240px"
          multiple
          placeholder="标签"
          clearable
        >
          <el-option
            v-for="dict in dict.type.goods_tag"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </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-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      ref="proTable"
      :height="tableHeight"
      border
      v-loading="loading"
      :data="postList"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="商品编码" min-width="120" align="center" prop="goodName">
        <template slot-scope="scope">
          <el-tooltip class="item" content="Top center" placement="top">
            <div slot="content" style="width: auto">
              {{ scope.row.sku }}
            </div>
            <div class="table-overflow">{{ scope.row.sku }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" min-width="180" align="center" prop="goodName">
        <template slot-scope="scope">
          <el-tooltip class="item" content="Top center" placement="top">
            <div slot="content" style="width: auto">
              {{ scope.row.goodName }}
            </div>
            <div class="table-overflow">{{ scope.row.goodName }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="品牌" min-width="140" align="center" prop="brandName">
        <template slot-scope="scope">
          <el-tooltip class="item" content="Top center" placement="top">
            <div slot="content" style="width: auto">{{ scope.row.brandName }}</div>
            <div class="table-overflow">{{ scope.row.brandName }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="型号" min-width="140" align="center" prop="spuName">
        <template slot-scope="scope">
          <el-tooltip class="item" content="Top center" placement="top">
            <div slot="content" style="width: auto">{{ scope.row.spuName }}</div>
            <div class="table-overflow">{{ scope.row.spuName }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="采购返利" width="180" align="center" prop="status">
        <template slot-scope="scope">
          <!-- <div v-for="(item, index) in scope.row.activities" :key="index"> -->
          {{ addPrice(scope.row.activities) }}
          <el-button
            class="detail-btn"
            type="text"
            size="mini"
            @click="showDetail(scope.row, scope.row.activities, 1)"
            v-if="addPrice(scope.row.activities) != '0.00元'"
            >查看</el-button
          >
          <!-- </div> -->
        </template>
      </el-table-column>
      <el-table-column
        label="加权平均成本价"
        min-width="160"
        align="center"
        prop="weightCostAvg"
      >
        <template slot="header" slot-scope="scope">
          加权平均成本价
          <el-tooltip
            class="item"
            effect="dark"
            content="(仓库1成本价*库存数量1+仓库2成本价*库存数量2+...)/总在库数量"
            placement="top"
          >
            <i class="el-icon-info"></i>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
        label="日初库存数量"
        min-width="120"
        align="center"
        prop="productSize"
      />
      <el-table-column
        label="仓库"
        width="255"
        fixed="right"
        align="center"
        prop="status"
      >
        <template slot="header" slot-scope="scope">
          仓库
          <el-tooltip class="item" effect="dark" placement="top">
            <div slot="content">
              1,串码分仓成本价<br />
              (采购单1价格*串码数量1+采购单2价格*串码数量2+...)/在库库存数量<br />
              2,非串码分仓成本价<br />
              (采购单1价格*数量1+采购单2价格*数量2+...)/在库库存数量<br />
            </div>
            <i class="el-icon-info"></i>
          </el-tooltip>
        </template>
        <template slot-scope="scope">
          <div v-for="(item, index) in scope.row.warehouses" :key="index">
            {{ item.warehouseName }}：{{ item.weightCost }}元/{{ item.productSize }}台
            <el-button
              class="detail-btn"
              type="text"
              size="mini"
              @click="showDetail(scope.row, item, 2)"
              >查看</el-button
            >
          </div>
        </template>
      </el-table-column>
    </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="采购返利详情"
      top="50px"
      :visible.sync="open"
      width="1100px"
      append-to-body
    >
      <el-table
        ref="activitedTable"
        :loading="activitedLoading"
        border
        :data="activitedList"
      >
        <el-table-column
          label="返利名称"
          min-width="180"
          align="center"
          prop="activitieName"
        >
          <template slot-scope="scope">
            <el-tooltip class="item" content="Top center" placement="top">
              <div slot="content" style="width: auto">
                {{ scope.row.activityCode }}/{{ scope.row.activityName }}
              </div>
              <div class="table-overflow">
                {{ scope.row.activityCode }}/{{ scope.row.activityName }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="返利时间" min-width="120" align="center" prop="startTime">
          <template slot-scope="scope">
            {{ scope.row.startTime.substring(5, 10) }}~{{
              scope.row.endTime.substring(5, 10)
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="返利活动状态"
          min-width="140"
          align="center"
          prop="activitieDate"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.status == 0">待提交</span>
            <span v-if="scope.row.status == 1">待审批</span>
            <span v-if="scope.row.status == 2">审批打回</span>
            <span v-if="scope.row.status == 3">启用</span>
            <span v-if="scope.row.status == 4">下线</span>
            <span v-if="scope.row.status == 5">挂起</span>
            <span v-if="scope.row.status == 6">变更待审批</span>
            <span v-if="scope.row.status == 7">变更审批打回</span>
            <span v-if="scope.row.status == 8">变更待提交</span>
          </template>
        </el-table-column>
        <el-table-column label="返利商品" min-width="140" align="center" prop="spuName">
          <template slot-scope="scope">
            <el-tooltip class="item" content="Top center" placement="top">
              <div slot="content" style="width: auto">
                {{ scope.row.skuNo }}/{{ scope.row.skuName }}
              </div>
              <div class="table-overflow">
                {{ scope.row.skuNo }}/{{ scope.row.skuName }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          label="返利类型"
          width="140"
          align="center"
          prop="rebateTypeCode"
        >
          <template slot-scope="scope">
            {{ rebateTypeCodeFilter(scope.row.rebateTypeCode) }}
          </template>
        </el-table-column>
        <el-table-column
          label="返利金额（元）/比例"
          min-width="200"
          align="center"
          prop="weightCostAvg"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.calcType == '固定金额'">
              返利金额：{{ scope.row.price || 0 }}元
            </div>
            <div v-else>
              每台返点：{{ scope.row.ratePrice || 0 }}%<br />预估返利金额{{
                scope.row.processPrice || 0
              }}元
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="110" align="center" prop="productSize">
          <template slot-scope="scope">
            <el-button
              class="detail-btn"
              type="text"
              size="mini"
              @click="avtivitedDetail(scope.row)"
              >详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>

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

    <el-dialog
      title="采购成本明细"
      top="50px"
      :visible.sync="open2"
      width="800px"
      append-to-body
    >
      <el-descriptions :column="2">
        <el-descriptions-item label="仓库">{{
          rowItem.warehouseName
        }}</el-descriptions-item>
        <el-descriptions-item label="商品编码">{{ rowDetail.sku }}</el-descriptions-item>
        <el-descriptions-item label="商品名称">{{
          rowDetail.goodName
        }}</el-descriptions-item>
      </el-descriptions>
      <el-table ref="wareHouseTable" border :data="wareHouseList">
        <el-table-column
          label="采购单号"
          min-width="180"
          align="center"
          prop="purchaseArriveCode"
        />
        <el-table-column
          label="采购价格"
          min-width="120"
          align="center"
          prop="purchasePrice"
        />
        <el-table-column
          label="入库时间"
          min-width="140"
          align="center"
          prop="purchaseArriveAt"
        />
        <el-table-column
          label="在库库存数量"
          width="140"
          align="center"
          prop="purchaseGoodNum"
        />
      </el-table>

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

<script>
import {
  weightCostList,
  getBrandNameList,
  getSpuList,
  warehouseList,
} from "@/api/goods/index";
import LoadMoreSelect from "@/components/LoadMoreSelect/index";
// import { getActivitieList } from "@/api/activitie/index";

export default {
  name: "CostPrice",
  dicts: ["sys_yes_no", "goods_tag"],
  components: {
    LoadMoreSelect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      activitedList: [],
      rowDetail: {},
      rowItem: {},
      // 弹出层标题
      title: "",
      attrList: {},
      // 是否显示弹出层
      open: false,
      open2: false,
      wareHouseList: [],
      activitedLoading: false,
      rebateTypeCodeList: [
        { code: "JLF", name: "激励返" },
        { code: "THGDF", name: "提货固定返" },
        { code: "THDLF", name: "提货达量返" },
        { code: "XSDLF", name: "销售达量返" },
        { code: "THJJTF", name: "提货价阶梯返" },
        { code: "ZDCMF", name: "指定串码返利" },
      ],
      // 查询参数
      queryParams: {
        queryDate: "",
        pageNum: 1,
        pageSize: 10,
        skus: "",
        skuNo: "",
        brandCodes: [],
        spuNos: [],
        tags: [],
      },
      brandNameList: [],
      spuList: [],
      spuList2: [],
      timer: null,
      tableHeight: "auto",
      warehouseLists: [],
      statusList: [
        { code: 0, name: "待提交" },
        { code: 1, name: "待审批" },
        { code: 2, name: "审批打回" },
        { code: 3, name: "启用" },
        { code: 4, name: "下线" },
        { code: 5, name: "挂起" },
        { code: 6, name: "变更待审批" },
        { code: 7, name: "变更审批打回" },
        { code: 8, name: "变更待提交" },
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近三天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit("pick", [end, start]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [end, start]);
            },
          },
          {
            text: "最近半个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
              picker.$emit("pick", [end, start]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [end, start]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [end, start]);
            },
          },
        ],
      },
    };
  },
  created() {
    if (localStorage.getItem("constPrice-query")) {
      this.queryParams = JSON.parse(localStorage.getItem("constPrice-query"));
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
    }
    const date = new Date();
    const year = date.getFullYear();
    const month =
      date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    const day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    this.today = year + "-" + month + "-" + day;
    this.queryParams.queryDate = year + "-" + month + "-" + day;

    this.getList();
    this.getBrandNameList();
  },
  mounted() {},
  methods: {
    rebateTypeCodeFilter(val) {
      const vals = this.rebateTypeCodeList.find((item) => {
        return item.code == val;
      });
      return vals.name;
    },
    addPrice(list) {
      let num = 0;
      list.forEach((item) => {
        num += parseFloat(item.processPrice);
      });
      return num.toFixed(2) + "元";
    },
    getBrandNameList() {
      getBrandNameList().then((res) => {
        this.brandNameList = res.data;
        if (localStorage.getItem("constPrice-query")) {
          this.brandChange(this.queryParams.brandCodes);
        }
      });
      warehouseList().then((res) => {
        this.warehouseLists = res.data.list;
      });
    },
    brandChange(value) {
      if (value.length != 0) {
        getSpuList(value).then((res) => {
          this.spuList = res.data;
        });
      } else {
        this.spuList = [];
      }
    },
    /** 查询岗位列表 */
    getList() {
      localStorage.setItem("constPrice-query", JSON.stringify(this.queryParams));

      this.loading = true;
      weightCostList(this.queryParams).then((response) => {
        this.postList = response.data.list;
        this.total = response.data.total;
        this.loading = false;

        this.$nextTick(() => {
          const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 210;
          console.log(height);
          this.tableHeight = height + "px";
        });
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        queryDate: "",
        pageNum: 1,
        pageSize: 10,
        skus: "",
        skuNo: "",
        brandCodes: [],
        spuNos: [],
        tags: [],
      };
      const date = new Date();
      const year = date.getFullYear();
      const month =
        date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
      const day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      this.today = year + "-" + month + "-" + day;
      this.queryParams.queryDate = year + "-" + month + "-" + day;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.postId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    showDetail(row, item, type) {
      this.rowDetail = row;
      this.rowItem = item;
      if (type == 1) {
        this.open = true;
        this.activitedLoading = true;
        this.activitedList = item;
        // getActivitieList({
        //   pageNum: 1,
        //   pageSize: 99,
        //   activitieName: "",
        //   brandCodes: [],
        //   endDate: "",
        //   rebateSendStatus: "",
        //   rebateTypeCode: "",
        //   skuNos: item.skuNo,
        //   skuNo: "",
        //   startDate: "",
        //   status: 3,
        //   suppliers: [],
        //   dateRange: null,
        // }).then((res) => {
        //   this.activitedList = res.data.activitieListResDTOS;
        //   this.activitedLoading = false;
        // });
      } else {
        this.wareHouseList = item.details;
        this.open2 = true;
      }
    },
    avtivitedDetail(row) {
      this.open = false;
      this.$router.push({
        path: "/activitie/detail",
        query: { activitieCode: row.activityCode },
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const data = { ...this.queryParams };
      delete data.pageNum;
      delete data.pageSize;
      this.newDownload(
        "weightCost/export",
        data,
        `商品加权成本价_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped>
.charts-box {
  height: 350px;
  margin-top: 30px;
}
.erpPrice > span {
  color: #409eff;
}
.iconEdit {
  cursor: pointer;
}
.app-container {
  padding-bottom: 50px;
}

.detail-btn {
  margin-left: 8px;
}
</style>
