<template>
  <div class="feed-summary-container">
    <div class="feed-summary-inner">
      <div class="left-side-menu">
        <project-side-menu :menuTree="menuTreeList" :menuOptions="menuOptions" :unique-opened="false" :default-active="currentNodeName"
          @select="menuSelect">
          <template slot="房建类成本科目-1">
            <img src="@/assets/images/projectCostLedger/icon_cost_detail_2.svg" alt="">
            <div class="project-sub-menu-title-text">房建类成本科目</div>
          </template>
          <template slot="未归类项目-1">
            <img src="@/assets/images/projectCostLedger/icon_cost_detail_3.svg" alt="">
            <div class="project-sub-menu-title-text">未归类项目</div>
          </template>
        </project-side-menu>
      </div>
      <div class="right-table-list-container">
        <div class="project-table-list-header">
          <div class="project-table-list-haeder-left">
            <!-- <el-date-picker v-model="recordDate" type="month" placeholder="选择月" format="yyyy年MM月" value-format="yyyy-MM"
              class="project-record-date" @change="timeChange"></el-date-picker> -->
            <el-select v-model="recordDate" placeholder="请选择年月" class="project-month-select-options" clearable @change="monthChange">
              <el-option v-for="item in monthList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div class="project-table-list-haeder-right">
            <!-- 实体工程材料单位换算 -->
            <el-button type="primary" size="medium" class="unit-conversion-btn" v-if="currentParentName.indexOf('实体工程材料') != -1">单位换算</el-button>
            <!-- 填写实际成本 -->
            <el-button type="primary" size="medium" class="actual-cost-btn" v-else>填写实际成本</el-button>
            <!-- 表头设置组件 -->
            <dsk-table-header-setting :settingList="formColum" @settingChange="settingChange"></dsk-table-header-setting>
          </div>
        </div>
        <!-- 数据列表部分 -->
        <div class="project-feedsummary-list-container">
          <dsk-skeleton v-if="tableLoading"></dsk-skeleton>
          <table-list-com :tableData="tableDataList" :formColum="formColum" v-else-if="!tableLoading" :maxHeight="true" :tableDataTotal="total"
            :paging="false">

          </table-list-com>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import ProjectSideMenu from "@/views/projectCostLedger/detail/components/ProjectSideMenu";
import { getFeedSummaryMenuTreeApi, getFeedSummaryMonthListApi, getFeedSummaryListApi } from "@/api/projectCostLedger";
import DskTableHeaderSetting from "@/components/DskTableHeaderSetting";
import DskSkeleton from "@/components/DskSkeleton";
import TableListCom from "@/components/TableListCom";
import { v4 } from 'uuid';
import dayjs from "dayjs";
import { cloneDeep } from "lodash-es";
export default {
  name: "feedSummary",
  props: {
    // 项目ID
    projectId: {
      type: String,
      required: true,
      default: ""
    },
    // 详情信息
    projectDetailInfo: {
      type: Object,
      default: () => ({})
    }
  },
  watch: {
    projectDetailInfo: {
      handler(newValue) {
        this.comProjectDetailInfo = newValue ? cloneDeep(newValue) : {};
        this.init(this.comProjectDetailInfo);
      },
      deep: true,
    },
    projectId: {
      handler(newValue) {
        this.comProjectId = newValue;
      }
    }
  },
  components: {
    ProjectSideMenu,
    DskTableHeaderSetting,
    TableListCom,
    DskSkeleton
  },
  data() {
    return {
      menuOptions: {
        nodeName: "name",
        nodeValue: "name",
      },
      comProjectDetailInfo: this.projectDetailInfo ? cloneDeep(this.projectDetailInfo) : {},
      comProjectId: this.projectId,
      menuTreeList: [],
      // 加载数据列表
      tableLoading: true,
      total: 0,
      // 列表表头
      formColum: [
        { label: '序号', prop: "staticSerialNumber", type: "index", lock: true, width: "53", fixed: false, uid: v4() },
        { label: '成本科目', prop: "cbSubjectName", width: "137", uid: v4() },
        { label: '公司编码', prop: "companyNo", width: "137", uid: v4() },
        { label: '集团编码', prop: "orgNo", width: "137", uid: v4() },
        { label: '名称', prop: "cbName", width: "232", uid: v4() },
        { label: '工作内容', prop: "jobContent", width: "341", uid: v4() },
        { label: '计算规则', prop: "calculationRule", width: "137", uid: v4() },
        { label: '单位', prop: "unit", width: "57", uid: v4() },
        { label: '甲供材料说明', prop: "materialDescription", width: "137", uid: v4() },
        {
          label: '计划成本', prop: "jhcb", width: "809", align: "center", slot: true, uid: v4(), children: [
            { label: '指导价格', prop: "guidePrice", width: "81", uid: v4() }
          ]
        },
      ],
      // 已记录月份集合
      monthList: [],
      // 源数据月份
      originMonthList: [],
      // 当前查询的数据月份
      recordDate: "",
      // 历史查询月份
      oldRecordDate: "",
      // 当前选中子菜单的父类名称
      currentParentName: "",
      // 当前选中的成本科目
      currentNodeName: "",
      // 数据列表
      tableDataList: []
    };
  },
  //可访问data属性
  created() {
    this.init(this.comProjectDetailInfo);
  },
  //计算集
  computed: {

  },
  //方法集
  methods: {
    async init(detail = {}) {
      try {
        const { projectId, cbStage } = detail;
        if (!projectId) return;
        const params = {
          projectId,
          cbStage
        };
        await this.getFeedSummaryMenuTree(params);
        await this.getFeedSummaryMonthList(params);
        await this.initDefaultSetting();
      } catch (error) {
        console.log(error);
      }
    },
    async initDefaultSetting() {
      try {
        const defaultCurrent = this.findMenuNode(this.menuTreeList, "结构劳务分包");
        // 默认选中结构劳务分包
        if (defaultCurrent) {
          this.currentNodeName = defaultCurrent.name;
          const params = this.createRequestConditions();
          await this.getFeedSummaryList(params);
        }
      } catch (error) {
        console.log(error);
      }
    },
    createRequestConditions() {
      const { projectId, cbStage } = this.comProjectDetailInfo;
      const params = {
        projectId,
        cbStage
      };
      params["cbSubjectName"] = this.currentNodeName;
      // 判断当月是否存在于server返回month集合中
      const _now = dayjs(new Date().valueOf()).format("YYYYMM");
      if (this.includeNowMonth(_now)) {
        params["recordDate"] = _now;
      }
      return params;
    },
    // 返回当前月是否在server month集合中
    includeNowMonth(time) {
      return this.originMonthList.includes(time);
    },
    findMenuNode(tree, nodeName) {
      for (const item of tree) {
        if (item.name == nodeName) return item;
        if (item.children instanceof Array) {
          const result = this.findMenuNode(item.children, nodeName);
          if (result) return result;
        }
      }
    },
    async getFeedSummaryList(params = {}) {
      try {
        this.tableLoading = true;
        const list = await getFeedSummaryListApi(params);
        if (list.code == 200 && list.data instanceof Array) {
          this.tableDataList = list.data;
          this.total = list.data.length;
        }
      } catch (error) {

      } finally {
        this.tableLoading = false;
      }
    },
    async getFeedSummaryMenuTree(params) {
      try {
        const result = await getFeedSummaryMenuTreeApi(params);
        if (result.code == 200 && result.data instanceof Array) {
          const _tempArray = result.data;
          this.menuTreeList = _tempArray;
        }
      } catch (error) {

      }
    },
    async getFeedSummaryMonthList(params) {
      try {
        const monthList = await getFeedSummaryMonthListApi(params);
        if (monthList.code == 200 && monthList.data instanceof Array) {
          const data = monthList.data;
          this.originMonthList = cloneDeep(data);
          const _now = dayjs(new Date().valueOf()).format("YYYYMM");
          this.recordDate = _now;
          this.oldRecordDate = _now;
          // 默认以当前月数据为准 若不包含当前月 需要手动push数据 
          if (!data.includes(_now)) {
            data.push(_now);
          }
          this.monthList = data.map(item => {
            return {
              label: dayjs(item).format("YYYY年MM月"),
              value: item
            };
          });
        }
      } catch (error) {

      }
    },
    monthChange(month) {
      // 当前月
      const _now = dayjs(new Date().valueOf()).format("YYYYMM");
      // 请求列表参数
      const params = this.createRequestConditions();
      // 清空了年月默认选中当前月
      if (!month) {
        this.recordDate = _now;
        // 如果命中的旧月份 等于当前月 说明清空的是当前月 不调用接口
        if (this.oldRecordDate == _now) return;
      } else {
        // 正常选择
        params["recordDate"] = month;
        // 记录历史切换年月
        this.oldRecordDate = month;
      }
      // 获取列表数据
      this.getFeedSummaryList(params);
    },
    menuSelect(currentId, currentTemp) {
      this.currentNodeName = currentId;
      const parentName = currentTemp.parent ? this.getCurrentType(currentTemp.parent) : currentId;
      if (parentName) this.currentParentName = parentName;
      // 请求数据列表
      const params = this.createRequestConditions();
      this.getFeedSummaryList(params);
    },
    getCurrentType(parent) {
      if (parent.level == 2) {
        return parent.nodeName;
      }
      if (parent.parent) {
        return this.getCurrentType(parent.parent);
      }
    },
    // 时间选择变化
    timeChange(time) {
      console.log(time);
    },
    // 表头设置变化
    async settingChange(use) {
      try {
        this.formColum = use;
      } catch (error) {

      }
    },
  },
}
</script>
<style lang="scss" scoped>
.feed-summary-container {
  width: 100%;
  height: 100%;

  .feed-summary-inner {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;

    .left-side-menu {
      width: 220px;
      min-width: 220px;
      height: 100%;
    }
    .right-table-list-container {
      width: calc(100% - 220px);
      height: 100%;
      box-sizing: border-box;
      background: #fff;
      padding: 16px;

      ::v-deep .project-table-list-header {
        margin-bottom: 16px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .project-table-list-haeder-left {
          display: flex;
          align-items: center;
          .project-record-date {
            width: 140px;
            .el-input__inner {
              height: 32px;
              line-height: 32px;
              padding: 0px 12px;
              border-radius: 2px;
              border-color: #dcdfe6;
              font-size: 14px;
              color: #232323;
              font-weight: 350;
            }
            .el-input__suffix {
              right: 12px;
              .el-input__icon {
                line-height: 32px;
                width: auto;
              }
            }
            .el-input__prefix {
              display: none;
            }
          }
          .project-month-select-options {
            width: 140px;
            .el-input__inner {
              height: 32px;
              line-height: 32px;
              padding: 0px 12px;
              border-radius: 2px;
              border-color: #dcdfe6;
              font-size: 14px;
              color: #232323;
              font-weight: 350;
            }
            .el-input__suffix {
              right: 12px;
              .el-input__icon {
                line-height: 32px;
                width: auto;
              }
            }
            .el-input__prefix {
              display: none;
            }
          }
        }

        .project-table-list-haeder-right {
          display: flex;
          align-items: center;

          .actual-cost-btn,
          .unit-conversion-btn {
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0px 12px;
            background-color: #0081ff;
            border-color: #0081ff;
            border-radius: 4px;
            color: #fff;
            font-size: 14px;
            font-weight: 350;
            margin-right: 16px;
          }
        }
      }

      .project-feedsummary-list-container {
        width: 100%;
        height: calc(100% - 48px);
        /* overflow: auto; */

        .dsk-skeleton-outer-container {
          padding: 0px;
          height: 100%;
        }

        ::v-deep .table-list-com-ins {
          height: 100%;
          .table-item {
            .el-table {
              th {
                height: 80px;
              }
              .cell {
                font-size: 14px;
                font-weight: 350;
              }
            }
          }
        }
      }
    }
  }
}
</style>
