<template>
  <div class="cost-summary-container">
    <!-- 按项目汇总  成本汇总切换 -->
    <div class="category-type-container">
      <div class="category-list-item" v-for="(type,index) of categoryList" :key="type.value"
        :class="{'is-current-category' : currentCategory == type.value}" @click.stop="currentCategoryChange(type.value)">{{type.label}}</div>
    </div>
    <!-- 成本菜单以及列表 -->
    <div class="cost-summary-content-container">
      <!-- 左侧菜单 -->
      <div class="left-side-menu">
        <project-side-menu ref="projectSideMenu" :menuTree="menuTreeList" :menuOptions="menuOptions" :unique-opened="false"
          :default-active="currentNodeValue" @select="menuSelect">
          <template slot="成本汇总-1">
            <img src="@/assets/images/projectCostLedger/icon_cost_detail_8.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-select v-model="expenseDate" placeholder="请选择年月" class="project-month-select-options" clearable @change="monthChange">
              <el-option v-for="item in monthList" :key="item.expenseDate" :label="item.label" :value="item.expenseDate">
              </el-option>
            </el-select>
          </div>
          <div class="project-table-list-haeder-right">

          </div>
        </div>
        <!-- 数据列表部分 -->
        <div class="project-feedsummary-list-container">
          <dsk-skeleton v-if="tableLoading"></dsk-skeleton>
          <el-form :model="dataForm" ref="costSummaryForm" :show-message="false" v-else-if="!tableLoading" class="feed-summary-form">
            <custom-table ref="costSummaryTable" :tableData="dataForm.tableDataList" :formColum="formColum" :max-height="true" :row-key="rowKey"
              :lazy="true" :load-fn="tableLazyLoad" :tree-options="treeOptions" :default-expand-all="false" :indent="8" :tableDataTotal="total"
              :paging="false" :cell-class-name="cellClassName">
            </custom-table>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import ProjectSideMenu from "@/views/projectCostLedger/detail/components/ProjectSideMenu";
import DskSkeleton from "@/components/DskSkeleton";
import CustomTable from "@/components/CustomTable";
import { getCostSummaryMenuTreeApi, getCostSummaryMonthListApi, getCostSummaryListApi } from "@/api/projectCostLedger";
import { v4 } from 'uuid';
import dayjs from "dayjs";
import { cloneDeep } from "lodash-es";
import { add } from "@/utils/decimal";

// 可编辑字段
const editPropNames = [
  "taxInclusiveExpense",
  "taxExclusiveExpense",
];

export default {
  name: "costSummary",
  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;
      }
    },
    expenseDate: {
      handler(newValue, oldValue) {
        this.oldExpenseDate = newValue;
      }
    }
  },
  components: {
    ProjectSideMenu,
    DskSkeleton,
    CustomTable
  },
  data() {
    return {
      // 当前分类 1 按项目汇总 2 成本汇总
      currentCategory: 1,
      categoryList: [
        {
          label: "按项目汇总",
          value: 1
        },
        {
          label: "成本科目汇总",
          value: 2
        },
      ],
      menuOptions: {
        nodeName: "cbName",
        nodeValue: "id",
      },
      comProjectDetailInfo: this.projectDetailInfo ? cloneDeep(this.projectDetailInfo) : {},
      comProjectId: this.projectId,
      menuTreeList: [],
      // 加载数据列表
      tableLoading: true,
      total: 0,
      // 列表表头
      formColum: [
        { label: '序号', prop: "number", minWidth: "53", uid: v4() },
        { label: '名称', prop: "cbName", width: "303", uid: v4(), showOverflowTooltip: true },
      ],
      monthList: [],
      rowKey: "id",
      // 列表懒加载配置
      treeOptions: {
        children: "children",
        hasChildren: "hasChildren"
      },
      // 源数据月份
      originMonthList: [],
      dataForm: {
        // 数据列表源数据
        tableDataList: [],
      },
      // 当前查询的数据月份
      expenseDate: "",
      // 历史查询月份
      oldExpenseDate: "",
      // 当前选中子菜单的父类名称
      currentParentName: "",
      // 当前选中的成本科目
      currentNodeValue: "",
      // 源数据列表
      originTableDataList: [],
      // 填写成本弹窗
      showAddActualCost: false,
      // 填写成本 编辑状态
      addActualCostEditStatus: false,
      // 当前选择的成本年份
      selectActualCostTime: "",
    };
  },
  //可访问data属性
  created() {
    this.init(this.comProjectDetailInfo);
  },
  //计算集
  computed: {

  },
  //方法集
  methods: {
    cellClassName({ row, column, rowIndex, columnIndex }) {
      // console.log(column);
      if (columnIndex == 0) {
        return "number-index-td";
      } else {
        const { property } = column;
        if (editPropNames.includes(property)) {
          return `can-edit-column-${property}`;
        }
      }
      return "";
    },
    getNowMonth() {
      return dayjs(new Date().valueOf()).format("YYYYMM");
    },
    // 返回当前月是否在server month集合中
    includeNowMonth(time) {
      return this.originMonthList.includes(time);
    },
    currentCategoryChange(category) {
      if (category == this.currentCategory) return;
      this.currentCategory = category;
    },
    async init(detail = {}, resetDate = "") {
      try {
        this.resetEditStatus();
        const { projectId, cbStage } = detail;
        if (!projectId) return;
        const params = {
          projectId,
          cbStage,
          cbType: this.currentCategory
        };
        await this.getCostSummaryMenuTree(params);
        await this.getCostSummaryMonthList(params);
        await this.initDefaultSetting(resetDate);
      } catch (error) {
        console.log(error);
      } finally {
        this.tableLoading = false;
      }
    },
    async initDefaultSetting(resetDate = "") {
      try {
        await this.$nextTick();
        const first = this.$refs["projectSideMenu"].getFirstLevelWithDeepId();
        const menus = this.$refs["projectSideMenu"].getResultMenuList();
        const defaultCurrent = this.findMenuNode(menus, first);
        // 默认选中结构劳务分包
        if (defaultCurrent) {
          this.currentNodeValue = defaultCurrent.nodeValue;
          const parentName = defaultCurrent.parent ? this.getCurrentType(defaultCurrent.parent) : defaultCurrent.nodeName;
          if (parentName) this.currentParentName = parentName;
          const params = this.createRequestConditions(resetDate);
          await this.getCostSummaryList(params);
        }
      } catch (error) {
        console.log(error);
      }
    },
    getCurrentType(parent) {
      if (parent.level == 2) {
        return parent.nodeName;
      }
      if (parent.parent) {
        return this.getCurrentType(parent.parent);
      }
    },
    findMenuNode(tree, nodeValue, targetName = "nodeValue") {
      for (const item of tree) {
        if (item[targetName] == nodeValue) return item;
        if (item.children instanceof Array) {
          const result = this.findMenuNode(item.children, nodeValue, targetName);
          if (result) return result;
        }
      }
    },
    // 创建查询条件
    createRequestConditions(resetDate = "") {
      const { projectId, cbStage } = this.comProjectDetailInfo;
      const params = {
        projectId,
        cbStage
      };
      params["id"] = this.currentNodeValue;
      params["cbType"] = this.currentCategory;
      // 判断当月是否存在于server返回month集合中 有传入的重置时间 采用重置时间
      const _now = this.getNowMonth();
      if (resetDate && this.includeNowMonth(resetDate)) {
        params["expenseDate"] = resetDate;
      } else if (this.includeNowMonth(_now)) {
        params["expenseDate"] = _now;
      }
      return params;
    },
    async getCostSummaryMenuTree(params) {
      try {
        const result = await getCostSummaryMenuTreeApi(params);
        if (result.code == 200 && result.data instanceof Array) {
          const _tempArray = result.data;
          const _tempMenu = {
            id: 0,
            cbName: this.currentCategory == 1 ? "成本汇总" : "房建类成本科目",
            children: _tempArray
          };
          this.menuTreeList = [_tempMenu];
        }
      } catch (error) {

      }
    },
    async getCostSummaryMonthList(params) {
      try {
        const monthList = await getCostSummaryMonthListApi(params);
        if (monthList.code == 200 && monthList.data instanceof Array) {
          const data = monthList.data;
          this.originMonthList = cloneDeep(data);
          const _now = this.getNowMonth();
          this.expenseDate = _now;
          // 默认以当前月数据为准 若不包含当前月 需要手动push数据
          if (!data.includes(_now)) {
            data.push({
              expenseDate: _now,
              isLock: 0
            });
          }
          // 年月排序
          let _tempMonthList = this.monthsSort(data);
          _tempMonthList = _tempMonthList.map(item => {
            return {
              label: dayjs(item.expenseDate).format("YYYY年MM月"),
              expenseDate: item.expenseDate,
              isLock: item.isLock
            };
          });
          this.monthList = _tempMonthList;
        }
      } catch (error) {

      }
    },
    monthChange(month) {
      // 当前月
      const _now = this.getNowMonth();
      // 请求列表参数
      const params = this.createRequestConditions();
      // 清空了年月 默认选中当前月
      if (!month) {
        this.expenseDate = _now;
        // 如果命中的旧月份 等于当前月 且 不处于编辑状态 说明清空的是默认查询月 不调用接口
        if (this.oldExpenseDate == _now && !this.addActualCostEditStatus) return;
      } else {
        // 正常选择
        params["expenseDate"] = month;
      }
      this.resetEditStatus();
      // 获取列表数据
      this.getCostSummaryList(params);
    },
    monthsSort(monthList) {
      const sortResult = monthList.sort((before, after) => {
        const _before = Object.prototype.toString.call(before) == "[object Object]" ? before["expenseDate"] : before;
        const _after = Object.prototype.toString.call(before) == "[object Object]" ? after["expenseDate"] : after;
        return parseInt(_after) - parseInt(_before);
      });
      return sortResult;
    },
    async getCostSummaryList(params = {}) {
      try {
        this.tableLoading = true;
        const list = await getCostSummaryListApi(params);
        if (list.code == 200 && list.data instanceof Array) {
          let _temp = list.data;
          const _mapList = new Map();
          // 如果有长度循环处理字段
          if (_temp.length) {
            _temp = _temp.map(item => {
              if (!item.hasChildren) {
                item.hasChildren = false;
              } else {
                // 有children
                item.hasChildren = true;
                if (item?.children?.length) {
                  item.children = item.children.map(childItem => {
                    childItem.hasChildren = childItem.hasChildren ? true : false;
                    return childItem;
                  });
                }
              };
              // 储存将子级储存到map 主动调用展开菜单
              item.hasChildren ? _mapList.set(item.id, item.children ? cloneDeep(item.children) : []) : null;
              delete item.children;
              return item;
            });
          }
          console.log(_temp);
          this.$set(this.dataForm, "tableDataList", cloneDeep(_temp));
          this.originTableDataList = cloneDeep(_temp);
          this.total = _temp.length;
          this.tableLoading = false;
          await this.$nextTick();
          const tableIns = this.$refs["costSummaryTable"].$refs["customTableRef"];
          if (tableIns) {
            _mapList.forEach((child, id) => {
              // 打开一级目录
              this.customResolve(id, child, tableIns);
            });
          }
        }
      } catch (error) {
        this.tableLoading = false;
        console.log(error);
      }
    },
    // 模拟 resolve 懒加载
    customResolve(id, child, tableIns) {
      let children = child;
      let newKey = id;
      let treeNodeMap = tableIns.store.states.lazyTreeNodeMap;
      let treeData = tableIns.store.states.treeData;
      //treeData 添加父子关系和状态
      let childrenids = Array.from(children).map(item => item.id);
      let metaInfo = {
        children: childrenids,
        display: true,
        expanded: true,
        lazy: true,
        level: "",
        loaded: true,
        loading: false
      };
      this.$set(treeData, newKey, metaInfo);
      //lazyTreeNodeMap中 添加数据
      this.$set(treeNodeMap, newKey, children);
      console.log(treeData, "treeData");
      console.log(treeNodeMap, "treeNodeMap");
    },
    async getCostSummaryListLazy(params = {}) {
      try {
        const list = await getCostSummaryListApi(params);
        if (list.code == 200 && list.data instanceof Array) {
          let _temp = list.data?.length ? list.data[0] : {};
          _temp = _temp.children?.length ? _temp.children : [];
          // 如果有长度循环处理字段
          if (_temp.length) {
            _temp = _temp.map(item => {
              if (!item.hasChildren) {
                item.hasChildren = false;
              } else {
                item.hasChildren = true;
              };
              return item;
            });
          }
          return _temp;
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 列表懒加载
    async tableLazyLoad(row, treeNode, resolve) {
      try {
        const { id } = row;
        const { cbType, expenseDate } = this.createRequestConditions();
        const params = {
          id,
          cbType
        };
        expenseDate ? params["expenseDate"] = expenseDate : null;
        const _lazyResult = await this.getCostSummaryListLazy(params);
        resolve(_lazyResult ? _lazyResult : null);
      } catch (error) {

      }
    },
    // 编辑状态下 进行了其它操作
    resetEditStatus() {
      // 当前需要编辑或者新增的成本年份
      const _selectActualCostTime = this.selectActualCostTime;
      this.addActualCostEditStatus = false;
      this.selectActualCostTime = "";
      /**
       * 判断 当前需要编辑 或者新增的成本年份是否存在于server返回的month数组中 不存在则删除 该月份 然后 选中当前月
       * 默认本月
      */
      if (!_selectActualCostTime) return;
      if (!this.originMonthList.includes(_selectActualCostTime) && _selectActualCostTime != this.getNowMonth()) {
        const index = this.monthList.findIndex(item => item.value == _selectActualCostTime);
        if (index != -1) {
          this.monthList.splice(index, 1);
          this.expenseDate = this.getNowMonth();
        }
      }
    },
    async menuSelect(currentId, currentTemp) {
      this.resetEditStatus();
      this.currentNodeValue = currentId;
      const parentName = currentTemp.parent ? this.getCurrentType(currentTemp.parent) : currentId;
      if (parentName) this.currentParentName = parentName;
      const params = this.createRequestConditions(this.expenseDate);
      this.getCostSummaryList(params);
    },
  },
}
</script>
<style lang="scss" scoped>
.cost-summary-container {
  width: 100%;
  height: 100%;
  overflow: hidden;

  .category-type-container {
    height: 64px;
    width: 100%;
    display: flex;
    align-items: center;
    padding: 16px;
    box-sizing: border-box;
    border-bottom: 1px solid #eeeeee;
    background: #fff;

    .category-list-item {
      height: 32px;
      padding: 0px 20px;
      color: #303133;
      font-size: 12px;
      font-weight: 400;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      box-sizing: border-box;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      transition: all 0.3s;

      &:nth-of-type(2n - 1) {
        border-right: unset !important;
        border-top-right-radius: 0px;
        border-bottom-right-radius: 0px;
      }

      &:nth-of-type(2n) {
        border-left: unset !important;
        border-top-left-radius: 0px;
        border-bottom-left-radius: 0px;
      }

      &.is-current-category {
        color: #fff;
        border: 1px solid #0081ff;
        background: #0081ff;
      }
    }
  }

  .cost-summary-content-container {
    width: 100%;
    height: calc(100% - 64px);
    display: flex;
    align-items: center;
    overflow: hidden;

    .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-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 {
        position: relative;
        width: 100%;
        height: calc(100% - 48px);
        overflow: auto;

        .feed-summary-form {
          height: 100%;
        }

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

        ::v-deep .custom-table-list-com-ins {
          .custom-table-item {
            .el-table {
              th {
                height: 40px;
              }
              .cell {
                font-size: 14px;
                font-weight: 350;
              }
              .number-index-td {
                .cell {
                  display: flex;
                  align-items: center;
                  .el-table__expand-icon {
                    margin-right: 5px;
                  }
                }
              }
              .inner-edit-input-item {
                margin-bottom: 0px;

                .el-form-item__content {
                  line-height: 32px;
                }

                &.is-error {
                  .el-input__inner {
                    &:focus {
                      border-color: #ff4949;
                    }
                  }
                }

                .el-input__inner {
                  line-height: 32px;
                  height: 32px;
                  border-radius: 2px;
                  padding-left: 8px;

                  &:focus {
                    border-color: #0081ff;
                  }
                }
                .el-input__clear {
                  line-height: 32px;
                }
              }
            }
          }
        }

        .project-action-field-bar {
          display: flex;
          align-items: center;

          .push-project-use {
            color: #0081ff;
            font-size: 14px;
            font-weight: 350;
            cursor: pointer;

            &.is-emty-quantities {
              cursor: not-allowed;
              color: rgba(35, 35, 35, 0.4);
            }
          }
        }
      }
    }
  }
}
</style>
