<template>
  <div class="analysis">
    <!-- 工作看板 -->
    <board :title="title[0]">
      <div>
        <work-infos :dataList="workInfos" @workInfoClick="handleWorkInfoClick">
        </work-infos>
        <div class="table-content">
          <table-content
            :tableItems="tableItems"
            :height="height"
            :shows="tableShows"
            :listData="tableData"
          >
            <template v-slot:handleState="slotProps">
              {{ slotProps.row.handleState ? "已处理" : "未处理" }}
            </template>
          </table-content>
        </div>
      </div>
    </board>

    <!-- 存栏情况 -->
    <board :title="title[1]">
      <div>
        <div>
          <!-- 存栏结构 -->
          <chart-inventory-pie :data="inventoryPieData"></chart-inventory-pie>
          <!-- 存栏变动 -->
          <chart-inventory-lines :data="inventoryLinesData">
          </chart-inventory-lines>
        </div>
        <div>
          <!-- 存栏计数 -->
          <inventory-items :data="inventoryItemsData"></inventory-items>
        </div>
      </div>
    </board>

    <!-- 生产情况 -->
    <board :title="title[2]">
      <!-- 环形图 -->
      <production-donuts :data="productionPercents"> </production-donuts>
      <!-- 8个格子 -->
      <production-items :data="productionItems"></production-items>
    </board>

    <!-- 经营分析 -->
    <board :title="title[3]">
      <!-- 成本分析 -->
      <div class="cost">
        <div class="cost-content">
          <div class="cost-left">
            <cost-pie :data="costPieData" :title="costTitles[costIndex]">
            </cost-pie>
          </div>
          <div class="cost-right">
            <cost-histogram
              :data="costHisData"
              :xAxisData="costTitles"
              @changeCostIndex="changeCostIndex"
            >
            </cost-histogram>
          </div>
        </div>
        <h3 class="label">成本分析</h3>
      </div>

      <!-- 重要指标 -->
      <div class="important">
        <div class="condition">
          <el-select
            size="small"
            v-model="importantValue"
            style="margin-right: 20px"
            @change="changeImportantValue"
          >
            <el-option
              v-for="item in importantOptions"
              :key="item.type"
              :label="item.label"
              :value="item.type"
            >
            </el-option>
          </el-select>
          <el-date-picker
            v-model="importantDates"
            size="small"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            @change="changeImportantDates"
          >
          </el-date-picker>
        </div>
        <div class="important-chart">
          <important-line :listData="importantData" v-bind="importantTitle">
          </important-line>
        </div>
      </div>

      <!-- 销售情况 -->
      <div class="sales">
        <div class="sales-title">销售</div>
        <div class="sales-condition">
          <el-date-picker
            v-model="getSalesDates"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
            size="small"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </div>
        <div class="sales-content">
          <div class="sales-left">
            <div class="up">
              <label>上月销售额</label>
              <span>{{ weekSales }}元</span>
              <div class="sales-change">
                <div>
                  <div
                    class="triangle-change"
                    :class="
                      weekSalesChange > 0 ? 'triangle-up' : 'triangle-down'
                    "
                  ></div>
                  <span :class="weekSalesChange > 0 ? 'color-up' : 'color-down'"
                    >{{ weekSalesChange }}%</span
                  >
                  &nbsp;&nbsp;&nbsp;环比上月
                </div>
              </div>
            </div>
            <div class="down">
              <label>上月销售量</label>
              <span>{{ weekSalesVolume }}头</span>
              <div class="sales-change">
                <div>
                  <div
                    class="triangle-change"
                    :class="
                      weekSalesVolumeChange > 0
                        ? 'triangle-up'
                        : 'triangle-down'
                    "
                  ></div>
                  <span
                    :class="
                      weekSalesVolumeChange > 0 ? 'color-up' : 'color-down'
                    "
                  >
                    {{ weekSalesVolumeChange }}%
                  </span>
                  &nbsp;&nbsp;&nbsp;环比上月
                </div>
              </div>
            </div>
          </div>
          <div class="sales-right">
            <sales-chart :data="salesChartData"></sales-chart>
          </div>
        </div>
      </div>
    </board>

    <!-- 应收排名 -->
    <!-- <board :title="title[4]">
      <table-content
        :tableItems="yingshouTableItems"
        :height="height"
        :shows="yingshouTableShows"
        :listData="yingshouTableData"
      >
      </table-content>
    </board> -->

    <!-- 应付排名 -->
    <board :title="title[5]">
      <table-content
        :tableItems="yingshouTableItems"
        :height="height"
        :shows="yingshouTableShows"
        :listData="yingfuTableData"
      >
      </table-content>
    </board>

    <!-- 安全库存报警 -->
    <board :title="title[6]">
      <table-content
        :tableItems="safetyTableItems"
        :height="height"
        :shows="safetyTableShows"
        :listData="safetyTableData"
        :empty-text="'暂无报警'"
      >
        <template #isWarning="slotProps">
          <el-tag
            :type="slotProps.row.isWarning ? 'success' : 'warning'"
            effect="dark"
          >
            {{ slotProps.row.isWarning ? "已报警" : "未报警" }}
          </el-tag>
        </template>
      </table-content>
      <table-footer
        :totals="total"
        :size="size"
        @sizeChange="sizeChange"
        @pageChange="pageChange"
      >
      </table-footer>
    </board>
  </div>
</template>

<script>
import Board from "components/board/index.vue";
import WorkInfos from "./analysis/WorkInfos.vue";
import TableContent from "components/newTable/TableContent.vue";
import ChartInventoryPie from "./analysis/ChartInventoryPie.vue";
import ChartInventoryLines from "./analysis/ChartInventoryLines.vue";
import InventoryItems from "./analysis/InventoryItems.vue";
import ProductionDonuts from "./analysis/ProductionDonuts.vue";
import ProductionItems from "./analysis/ProductionItems.vue";
import CostPie from "./analysis/CostPie.vue";
import CostHistogram from "./analysis/CostHistogram.vue";
import ImportantLine from "./analysis/ImportantLine.vue";
import SalesChart from "./analysis/SalesChart.vue";
import TableFooter from "../../components/TableFooter";

import { tableItems, tableShows } from "./analysis/table.config";
import {
  yingshouTableItems,
  yingshouTableShows,
} from "./analysis/yingshouTable.config";
import {
  safetyTableItems,
  safetyTableShows,
} from "./analysis/safetyTable.config";
// import { formItems } from './analysis/salesXForm.config'

import {
  getInventoryLines,
  getInventoryAndProduct,
  // getSalesChange,
  // getSalesChart,
  // getCosts,
  // getYingShou,
  getYingFu,
} from "utils/api";
import {
  getWorkTotal,
  getWorkInfos,
  getSafeInventory,
  getProductionCondition,
  getImportantData,
  getCostData,
  getTheSales,
} from "utils/chenApi";

export default {
  name: "Analysis",
  components: {
    Board,
    WorkInfos,
    TableContent,
    ChartInventoryPie,
    ChartInventoryLines,
    InventoryItems,
    ProductionDonuts,
    ProductionItems,
    CostPie,
    CostHistogram,
    ImportantLine,
    // XForm,
    SalesChart,
    TableFooter,
  },
  data() {
    return {
      title: [
        "工作看板",
        "存栏情况",
        "生产情况",
        "经营分析",
        "应收排名",
        "应付排名",
        "安全库存报警",
      ],
      workInfos: [],
      tableItems: [],
      tableShows: {},
      height: 300,
      tableData: [],
      // 存栏情况
      inventoryLinesData: {}, // 折线图数据
      inventoryPieData: [], // 环形图数据
      inventoryItemsData: [], // 下面块图的数据
      // 生产情况
      productionPercents: [], // 百分比
      productionItems: [], // 下面块图的数据
      // 经营分析
      costTitles: ["总成本", "基础猪群", "保育猪群", "育肥猪群", "后备猪群"], // 成本分析 - 被选中的名字
      costIndex: 0, // 成本分析 - 名字数组的 index
      costPieData: {}, // 经营分析 - 成本分析环形图
      costHisData: [], // 经营分析 - 柱状图
      // 重要指标
      importantOptions: [
        {
          type: 1,
          label: "配种指标",
        },
        {
          type: 2,
          label: "分娩指标",
        },
        {
          type: 3,
          label: "断奶指标",
        },
        {
          type: 4,
          label: "成活率指标",
        },
      ],
      importantValue: 1,
      importantDates: [],
      importantData: [], // 重要指标折线图数据
      importantTitle: {}, // 重要指标的名称
      // 销售额
      // salesFormItems: [],
      salesDay: 2, //默认选择本周
      weekSales: 1545252,
      weekSalesChange: 10,
      weekSalesVolume: 1000,
      weekSalesVolumeChange: -10,
      getSalesDates: [], // 销售图的时间选择
      pickerOptions: {
        // 快捷选项
        shortcuts: [
          {
            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 * 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]);
            },
          },
        ],
      },
      salesChartData: {}, // 销售图的数据
      // 应收排名
      yingshouTableItems: [],
      yingshouTableShows: {},
      yingshouTableData: [],
      // 应付排名
      yingfuTableData: [],
      // 安全库存报警
      safetyTableItems: [],
      safetyTableShows: {},
      safetyTableData: [],
      total: 0,
      size: 20,
      pageNum: 1,
    };
  },
  mounted() {
    // this.salesFormItems = formItems
    this.tableItems = tableItems;
    this.tableShows = tableShows;
    this.yingshouTableItems = yingshouTableItems;
    this.yingshouTableShows = yingshouTableShows;
    this.safetyTableItems = safetyTableItems;
    this.safetyTableShows = safetyTableShows;
    /** 获取网络请求数据 */
    this.initInventoryLines();
    this.initInventoryAndProduct();
    // this.initSalesChange();
    // this.initSalesChart();
    // this.initYingShou();
    this.initYingFu();
    this.initWorkBoard(); // 工作看板
    this.initSafeInventory(); // 安全库存报警
    this.initProductionCondition(); // 生产情况
    this.initImportantData(); // 重要指标
    this.initCostData(); // 成本分析
    this.initTheSales(); // 销售情况
  },
  methods: {
    handleWorkInfoClick(item) {
      console.log(item);
    },
    // 修改size
    sizeChange(val) {
      this.size = val;
      this.init();
    },
    // 修改页数
    pageChange(val) {
      this.pageNum = val;
      this.init();
    },
    // 销售额选中日期
    salesSetDay(data) {
      this.salesDay = data;
      // console.log(this.salesDay);
    },
    // 销售额选中日周月
    salesOnClickType(data) {
      // console.log(data);
    },
    // 工作看板
    initWorkBoard() {
      getWorkTotal({}).then(async (res) => {
        this.workInfos = [
          {
            label: "报警信息",
            number: res.data.warning?.planTimes || 0,
          },
          {
            label: "日常计划",
            number: res.data.daily?.planTimes || 0,
          },
          {
            label: "转舍记录",
            number: res.data.transferHouse?.planTimes || 0,
          },
          {
            label: "普免计划",
            number: res.data.ordinary?.planTimes || 0,
          },
          {
            label: "免疫计划",
            number: res.data.immune?.planTimes || 0,
          },
        ];
        const result = await getWorkInfos({});
        this.tableData = result.data;
      });
    },
    // 存栏情况 - 存栏变动折线图数据请求
    initInventoryLines() {
      getInventoryLines({}).then((res) => {
        if (res.code === 10000) {
          this.inventoryLinesData = res.data;
        } else {
          this.inventoryLinesData = {
            boarStock: [],
            fatpigStock: [],
            griceStock: [],
            month: [],
            pigletStock: [],
            sowStock: [],
          };
        }
      });
    },
    // 存栏情况 + 生产情况
    initInventoryAndProduct() {
      getInventoryAndProduct({}).then((res) => {
        if (res.code === 10000) {
          // this.inventoryLinesData = res.data
          // console.log(res.data);
          const undefinedData = {
            stockQuantity: 0,
          };
          // this.inventoryPieData = res.data.slice(0, 6)
          this.inventoryPieData = [
            res.data["sow_stock"] || undefinedData,
            res.data["boar_stock"] || undefinedData,
            res.data["grice_stock"] || undefinedData,
            res.data["piglet_stock"] || undefinedData,
            res.data["fatpig_stock"] || undefinedData,
          ];
          // console.log("object", this.inventoryPieData);
          this.inventoryItemsData = [
            res.data["sow_stock"] ? res.data["sow_stock"].stockQuantity : 0,
            res.data["sow_stock_1"] ? res.data["sow_stock_1"].stockQuantity : 0,
            res.data["sow_stock_2"] ? res.data["sow_stock_2"].stockQuantity : 0,
            res.data["sow_stock_3"] ? res.data["sow_stock_3"].stockQuantity : 0,
            res.data["boar_stock"] ? res.data["boar_stock"].stockQuantity : 0,
            res.data["business_stock"]
              ? res.data["business_stock"].stockQuantity
              : 0,
          ];
          // this.productionPercents = [
          //   res.data[12].rate * 100,
          //   res.data[13].rate * 100,
          //   res.data[14].rate * 100,
          //   res.data[15].rate * 100,
          //   res.data[16].rate * 100,
          // ];
          // this.productionPercents = [res.data[12].rate*100, res.data[13].rate*100, res.data[14].rate*100, res.data[15].rate*100, res.data[16].rate*100]
          // this.productionItems = [res.data[17].stockQuantity, res.data[18].stockQuantity, res.data[19].stockQuantity, res.data[20].stockQuantity, res.data[21].stockQuantity, res.data[22].stockQuantity, res.data[23].stockQuantity, res.data[24].stockQuantity]
        } else {
          // this.inventoryLinesData = {
          //   boarStock: [],
          //   fatpigStock: [],
          //   griceStock: [],
          //   month: [],
          //   pigletStock: [],
          //   sowStock: []
          // }
        }
      });
    },
    // // 经营分析 - 销售改变
    // initSalesChange() {
    //   getSalesChange({}).then((res) => {
    //     if (res.code === 10000) {
    //       this.weekSales = res.data.quantityAll;
    //       this.weekSalesChange = res.data.quantityType
    //         ? res.data.quantityPercentage
    //         : -res.data.quantityPercentage;
    //       this.weekSalesVolume = res.data.saleAll;
    //       this.weekSalesVolumeChange = res.data.saleType
    //         ? res.data.salePercentage
    //         : -res.data.salePercentage;
    //     } else {
    //       this.weekSales = 0;
    //       this.weekSalesChange = 0;
    //       this.weekSalesVolume = 0;
    //       this.weekSalesVolumeChange = 0;
    //     }
    //   });
    // },
    // // 经营分析 - 销售情况图
    // initSalesChart() {
    //   const params = {
    //     beginDate: this.getSalesDates[0] || "",
    //     endDate: this.getSalesDates[1] || "",
    //   };
    //   console.log("我要放参数了", params);
    //   getSalesChart(params).then((res) => {
    //     if (res.code === 10000) {
    //       this.salesChartData = res.data;
    //       console.log(this.salesChartData);
    //     }
    //   });
    // },
    // 经营分析 - 成本分析
    initCostData() {
      getCostData({}).then((res) => {
        // console.log(res);
        if (res.code === 10000) {
          this.costHisData = [
            res.data["total"],
            res.data["baseGroup"],
            res.data["pigletGroup"],
            res.data["fattenPig"],
            res.data["replaceGilt"],
          ];
          this.costPieData = this.costHisData[this.costIndex];
        }
      });
    },
    // // 应收排名
    // initYingShou() {
    //   getYingShou({}).then((res) => {
    //     console.log("应收", res);
    //     if (res.code === 10000) {
    //       this.yingshouTableData = res.data;
    //     }
    //   });
    // },
    // 应付排名
    initYingFu() {
      getYingFu({}).then((res) => {
        // console.log("应付", res);
        if (res.code === 10000) {
          this.yingfuTableData = res.data;
        }
      });
    },
    // 安全库存报警
    initSafeInventory() {
      getSafeInventory({
        current: this.pageNum,
        size: this.size,
      }).then((res) => {
        // console.log(res);
        if (res.code === 10000) {
          this.safetyTableData = res.data.records;
          this.total = res.data.total;
        }
      });
    },
    // 生产情况
    initProductionCondition() {
      getProductionCondition({}).then((res) => {
        // console.log(res.data);
        if (res.code === 10000) {
          this.productionPercents = [
            { ...res.data["grice_rate"], color: "rgb(112,249,250)" },
            { ...res.data["piglet_rate"], color: "rgb(51, 211, 137)" },
            { ...res.data["fatpig_rate"], color: "rgb(255, 125, 0)" },
            { ...res.data["break_rate"], color: "rgb(2, 167, 240)" },
            { ...res.data["breed_rate"], color: "rgb(112, 0, 217)" },
          ];
          this.productionItems = [
            res.data["avg_farrow_1"].stockQuantity,
            res.data["avg_farrow_2"].stockQuantity,
            res.data["avg_farrow_3"].stockQuantity,
            res.data["break_grice"].stockQuantity,
            res.data["avg_weight"].stockQuantity,
            res.data["avg_weight"].stockQuantity, // FIXME: 没有数据，随便放一个先
            res.data["nest_times"].stockQuantity,
            res.data["psy"].stockQuantity,
          ];
        }
      });
    },
    // 重要指标折线图
    initImportantData() {
      getImportantData({
        startDate: this.importantDates[0],
        endDate: this.importantDates[1],
        type: this.importantValue,
      }).then((res) => {
        const types = [
          [
            {
              type: "break_rate",
              name: "七日断配率",
            },
          ],
          [
            {
              type: "avg_farrow_1",
              name: "平均窝产仔猪数",
            },
            {
              type: "avg_farrow_2",
              name: "平均窝产活仔数",
            },
            {
              type: "avg_farrow_3",
              name: "平均窝产正常仔数",
            },
          ],
          [
            {
              type: "avg_weight",
              name: "平均断奶窝重",
            },
            {
              type: "break_grice",
              name: "窝断奶仔猪数",
            },
          ],
          [
            {
              type: "fatpig_rate",
              name: "肥猪成活率",
            },
            {
              type: "grice_rate",
              name: "产房成活率",
            },
            {
              type: "piglet_rate",
              name: "保育成活率",
            },
          ],
        ];
        this.importantData = [];
        types[this.importantValue - 1].forEach((item) => {
          this.importantData.push({
            ...res.data[item.type],
            name: item.name, // 各项名称
          });
        });
        this.importantTitle = {
          isPercentage: res.data["isPercentage"],
          isWeight: res.data["isWeight"],
          isHead: res.data["isHead"],
        };
        // console.log("重要指标数据----------------", this.importantTitle);
      });
    },
    // 重要指标的 type 改变
    changeImportantValue() {
      this.initImportantData();
    },
    // 重要指标的时间改变
    changeImportantDates() {
      this.initImportantData();
    },
    // 成本分析 - 数据改变
    changeCostIndex(value) {
      this.costIndex = value;
      this.costPieData = this.costHisData[value];
    },
    // 销售情况
    initTheSales() {
      getTheSales({
        type: this.getSalesDates[0] ? 3 : 2,
        startDate: this.getSalesDates[0] || undefined,
        endDate: this.getSalesDates[1] || undefined,
      }).then((res) => {
        if (res.code === 10000) {
          this.weekSales = res.data.money;
          this.weekSalesChange = res.data.moneyPercent;
          this.weekSalesVolume = res.data.quantity;
          this.weekSalesVolumeChange = res.data.quantityPercent;
          // console.log("救命");
          this.salesChartData = {
            moneyList: res.data.moneyList,
            moneyList1: res.data.moneyList1,
            quantityList: res.data.quantityList,
            timeList: res.data.timeList,
          };
          // console.log(this.salesChartData);
        }
      });
    },
  },
  watch: {
    getSalesDates(newValue) {
      this.getSalesDates = newValue;
      this.initTheSales();
    },
  },
};
</script>

<style scoped>
.analysis {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 20px;
}
.table-content {
  padding: 10px 15px 12px;
}

/* 成本分析echarts图排列 */
.cost {
  border-bottom: 1px solid rgba(228, 228, 228, 1);
  position: relative;
}
.cost > .select {
  position: absolute;
  right: 0;
  margin: 20px;
}
.cost-content {
  padding-top: 20px;
  display: flex;
}
.cost-left {
  flex: 1;
}
.cost-right {
  flex: 1;
}
.cost > .label {
  text-align: center;
  font-weight: bold;
  font-size: 18px;
}
/* 重要指标 */
.important {
  padding: 20px;
  position: relative;
  border-bottom: 1px solid rgba(228, 228, 228, 1);
}
.important > .condition {
  position: absolute;
  right: 0;
  margin-right: 20px;
}
.important-chart {
  margin-top: 20px;
}
/* 销售情况 */
.sales {
  padding: 20px;
  padding-bottom: 0;
}
.sales-title {
  padding-left: 20px;
  font-size: 18px;
  font-weight: bolder;
}
.sales-condition {
  margin-left: 250px;
}
.sales-content {
  padding-top: 20px;
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}
.sales-left {
  width: 15%;
  line-height: 25px;
  padding-top: 30px;
}
.sales-left > .up {
  margin-bottom: 20px;
}
.sales-left > .up > label,
.sales-left > .down > label {
  display: block;
  text-align: center;
  font-size: 13px;
  color: #999;
}
.sales-left > .up > span,
.sales-left > .down > span {
  display: block;
  text-align: center;
  font-size: 16px;
  color: #333;
}
.sales-left > .up > .sales-change,
.sales-left > .down > .sales-change {
  display: flex;
  justify-content: space-around;
  font-size: 13px;
}
/* 三角形 */
.triangle-change {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-style: solid;
  border-width: 8px;
  margin-right: 20px;
}
.triangle-up {
  border-color: transparent transparent rgb(238, 16, 16) transparent;
}
.triangle-down {
  border-color: rgb(2, 112, 2) transparent transparent transparent;
  position: relative;
  top: 7px;
}
.color-up {
  color: rgb(238, 16, 16);
}
.color-down {
  color: rgb(2, 112, 2);
}
/* 销售情况右侧 */
.sales-right {
  width: 85%;
  border-left: 1px solid rgba(228, 228, 228, 1);
  height: 300px;
}
</style>
