<template>
  <div class="cost-summary-container">
    <!-- 按项目汇总  成本汇总切换 -->
    <div class="category-type-container">
      <el-button class="category-list-item" v-for="(type, index) of categoryList" :key="type.value" :disabled="type.disabled"
        :class="{ 'is-current-category': currentCategory == type.value }" @click.stop="currentCategoryChange(type.value)">{{ type.label }}</el-button>
    </div>
    <!-- 成本菜单以及列表 -->
    <div class="cost-summary-content-container" v-if="!show">
      <!-- 左侧菜单 -->
      <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>
          <!-- 锁定成本 导出excel 编辑成本 -->
          <div class="project-table-list-haeder-right">
            <div class="lock-cost-btn" :class="{ 'current-month-lock': currentMonthLock || !hasMenuData }"
              @click="!currentMonthLock && hasMenuData ? lockCostHandler() : ''">锁定成本
            </div>
            <div class="export-excel-btn" :class="{'btn-is-disable' : !hasMenuData}" @click="!hasMenuData ? '' : exportExcel()">
              导出Excel表</div>
            <div class="edit-cost-btn" :class="{'btn-is-disable' : !hasMenuData}"
              @click="hasMenuData ? (addActualCostEditStatus ? saveCostModify() : editCost()) : ''">
              {{ addActualCostEditStatus ? "保存成本" : "编辑成本" }}
            </div>
          </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"
              :default-expand-all="true" :indent="8" :tableDataTotal="total" :paging="false" :cell-class-name="cellClassName">
              <!-- 不含税成本合价 -->
              <template slot="taxExclusiveTotal" slot-scope="scope">
                {{$decimalFormat(scope.row.taxExclusiveTotal)}}
              </template>
              <!-- 成本税金合价 -->
              <template slot="cbTaxesTotal" slot-scope="scope">
                {{$decimalFormat(scope.row.cbTaxesTotal)}}
              </template>
              <!-- 含税成本合价 -->
              <template slot="taxInclusiveTotal" slot-scope="scope">
                {{$decimalFormat(scope.row.taxInclusiveTotal)}}
              </template>
              <!-- 含税成本平米指标 -->
              <template slot="taxInclusivePmTarget" slot-scope="scope">
                {{$decimalFormat(scope.row.taxInclusivePmTarget)}}
              </template>
              <!-- 本月费用（含税） -->
              <template slot="taxInclusiveExpense" slot-scope="scope">
                <!-- 本月费用（含税）编辑单元格 -->
                <el-form-item :prop="`tableDataList.${getTableTreeProp(dataForm.tableDataList, scope.row.id)}.taxInclusiveExpense`"
                  :rules="checkRules.amountCheck" v-if="addActualCostEditStatus" class="inner-edit-input-item">
                  <el-input placeholder="请输入" v-model="scope.row.taxInclusiveExpense" clearable
                    @input="v => editIptValueRectify(v, scope.row, 'taxInclusiveExpense')"></el-input>
                </el-form-item>
                <span v-else-if="!addActualCostEditStatus">{{$decimalFormat(scope.row.taxInclusiveExpense)}}</span>
              </template>
              <!-- 本月费用（不含税） -->
              <template slot="taxExclusiveExpense" slot-scope="scope">
                <el-form-item :prop="`tableDataList.${getTableTreeProp(dataForm.tableDataList, scope.row.id)}.taxExclusiveExpense`"
                  :rules="checkRules.amountCheck" v-if="addActualCostEditStatus" class="inner-edit-input-item">
                  <el-input placeholder="请输入" v-model="scope.row.taxExclusiveExpense" clearable
                    @input="v => editIptValueRectify(v, scope.row, 'taxExclusiveExpense')"></el-input>
                </el-form-item>
                <span v-else-if="!addActualCostEditStatus">{{$decimalFormat(scope.row.taxExclusiveExpense)}}</span>
              </template>
              <!-- 截止本月费用（含税） -->
              <template slot="taxInclusiveExpenseTotal" slot-scope="scope">
                {{$decimalFormat(scope.row.taxInclusiveExpenseTotal)}}
              </template>
              <!-- 截止本月费用（不含税） -->
              <template slot="taxExclusiveExpenseTotal" slot-scope="scope">
                {{$decimalFormat(scope.row.taxExclusiveExpenseTotal)}}
              </template>
            </custom-table>
          </el-form>
        </div>
      </div>
    </div>

    <div class="no-data">
      <div class="no-data-box" v-if="show">
        <img :src="noData" alt="暂未获取物料数据（每月20号获取）" />
        <span>暂未获取物料数据（每月20号获取）</span>
      </div>
    </div>

    <!-- 锁定前提示 -->
    <lock-cost-tip v-model="lockCostTipDialog" :tip-content="lockCostTipDialogContent" @ok="okLock"
      @update:lockCostTipDialog="lockCostTipDialogClose"></lock-cost-tip>

    <!-- 选择编辑的成本月份弹窗 -->
    <edit-cost-month-select v-model="editCostMonthSelectDialog" :project-create-time="projectDetailInfo.createTime" :disable-months="disableMonths"
      @timeSelect="timeSelect" @dialogStatusChange="dialogStatusChange"></edit-cost-month-select>

  </div>
</template>
<script>
import ProjectSideMenu from "@/views/projectCostLedger/detail/components/ProjectSideMenu";
import DskSkeleton from "@/components/DskSkeleton";
import CustomTable from "@/components/CustomTable";
import EditCostMonthSelect from "@/views/projectCostLedger/detail/components/CostSummary/components/CostMonthSelect";
import LockCostTip from "@/views/projectCostLedger/detail/components/CostSummary/components/LockCostTip";
import { getCostSummaryMenuTreeApi, getCostSummaryMonthListApi, getCostSummaryAllListApi, validateBeforeCostLockApi, getLockMonthListApi, setCostLockApi, exportCostLockExcelApi, saveCostModifyApi } 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,
    LockCostTip,
    EditCostMonthSelect
  },
  data() {
    const amountCheckValidator = (rule, value, callback) => {
      // 有值才进行验证
      if (value || value == "0") {
        const reg = /^(?!0\d)(?!0*\.0*$)\d+(\.\d+)?$/;
        if (!reg.test(value)) return callback(new Error("请输入正确的数值"));
      }
      callback();
    };
    return {
      noData: require("@/assets/images/detail/noData.png"),
      // 当前分类 1 按项目汇总 2 成本汇总
      currentCategory: 1,
      categoryList: [
        {
          label: "按项目汇总",
          disabled:false,
          value: 1
        },
        {
          label: "成本科目汇总",
          disabled:false,
          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: "80", uid: v4(), fixed: "left" },
        { label: '名称', prop: "cbName", width: "303", uid: v4(), showOverflowTooltip: true, fixed: "left" },
        { label: '不含税成本合价', prop: "taxExclusiveTotal", width: "182", uid: v4(), slot: true },
        { label: '成本税金合价', prop: "cbTaxesTotal", width: "182", uid: v4(), slot: true },
        { label: '含税成本合价', prop: "taxInclusiveTotal", width: "182", uid: v4(), slot: true },
        { label: '成本占比', prop: "cbProportion", width: "182", uid: v4() },
        { label: '含税成本平米指标', prop: "taxInclusivePmTarget", width: "182", uid: v4(), slot: true },
        { label: '备注', prop: "remark", width: "182", uid: v4() },
        { label: '本月费用（含税）', prop: "taxInclusiveExpense", width: "182", uid: v4(), slot: true },
        { label: '本月费用（不含税）', prop: "taxExclusiveExpense", width: "182", uid: v4(), slot: true },
        { label: '截止本月费用（含税）', prop: "taxInclusiveExpenseTotal", width: "182", uid: v4(), slot: true },
        { label: '截止本月费用（不含税）', prop: "taxExclusiveExpenseTotal", width: "182", uid: v4(), slot: true },
      ],
      monthList: [],
      // 源数据月份
      originMonthList: [],
      // 已经锁定的成本月份
      lockMonthList: [],
      rowKey: "id",
      // 列表懒加载配置
      dataForm: {
        // 数据列表源数据
        tableDataList: [],
      },
      // 当前查询的数据月份
      expenseDate: "",
      // 历史查询月份
      oldExpenseDate: "",
      // 当前选中子菜单的父类名称
      currentParentId: "",
      // 当前选中的成本科目
      currentNodeValue: "",
      // 源数据列表
      originTableDataList: [],
      // 填写成本 编辑状态
      addActualCostEditStatus: false,
      // 当前选择的成本年份
      selectActualCostTime: "",
      // 锁定成本前提示弹窗
      lockCostTipDialog: false,
      // 锁定成本前提示弹窗文本内容
      lockCostTipDialogContent: "",
      // 编辑成本选择月份弹窗
      editCostMonthSelectDialog: false,
      // 被锁定的成本月份
      disableMonths: [],
      // 编辑数据验证规则
      checkRules: {
        amountCheck: [
          { trigger: ["change"], validator: amountCheckValidator }
        ]
      },
      // 竖向滚动条最后的位置
      lastScrollTop: 0,
      show:false,
    };
  },
  //可访问data属性
  created() {
    const { projectId, cbStage } = this.comProjectDetailInfo;
    if (!projectId) return;
    const params = {
      projectId,
      cbStage,
      cbType: this.currentCategory
    };
    this.getCostSummaryMenuTree(params);
  },
  //计算集
  computed: {
    // 查看当前月是否是锁定状态 lock为true 不能锁定 反之可以
    currentMonthLock() {
      return this.lockMonthList.includes(this.expenseDate);
    },
    // 是否有科目菜单
    hasMenuData() {
      return this.menuTreeList.length ? true : false;
    }
  },
  //方法集
  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.find(item => item.expenseDate == time);
    },
    // 按项目汇总 按成本科目汇总
    currentCategoryChange(category) {
      if (category == this.currentCategory) return;
      this.currentCategory = category;
      this.resetEditStatus();
      this.tableLoading = true;
      this.resetTableData();
      this.init(this.comProjectDetailInfo);
    },
    resetTableData() {
      this.$set(this.dataForm, "tableDataList", []);
      const data = this.$options.data.call(this);
      this.originTableDataList = data.originTableDataList;
      this.total = 0;
      this.monthList = data.monthList;
      this.originMonthList = data.originMonthList;
      this.disableMonths = data.disableMonths;
    },
    async init(detail = {}, resetDate = "", saveReset = false) {
      try {
        this.resetEditStatus(saveReset);
        const { projectId, cbStage } = detail;
        if (!projectId) return;
        const params = {
          projectId,
          cbStage,
          cbType: this.currentCategory
        };
        // await this.getCostSummaryMenuTree(params);
        await this.getCostSummaryMonthList(params, saveReset);
        await this.getLockMonthList(params);
        await this.initDefaultSetting(resetDate, saveReset);
      } catch (error) {
        console.log(error);
      } finally {
        this.tableLoading = false;
      }
    },
    async initDefaultSetting(resetDate = "", saveReset = false) {
      try {
        await this.$nextTick();
        const first = saveReset ? this.currentNodeValue : this.$refs["projectSideMenu"].getFirstLevelWithDeepId();
        const menus = this.$refs["projectSideMenu"].getResultMenuList();
        const defaultCurrent = this.findMenuNode(menus, first);
        // 默认选中第一层级 第一个子菜单
        if (defaultCurrent) {
          this.currentNodeValue = defaultCurrent.nodeValue;
          const parentId = defaultCurrent.parent ? this.getCurrentType(defaultCurrent.parent) : defaultCurrent.nodeName;
          if (parentId) this.currentParentId = parentId;
          const params = this.createRequestConditions(resetDate);
          await this.getCostSummaryList(params);
        }
      } catch (error) {
        console.log(error);
      }
    },
    getCurrentType(parent) {
      if (parent.level == 2) {
        return parent.nodeValue;
      }
      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);
          return result;
        }
      }
      return null;
    },
    // 创建查询条件
    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 getMenuTree(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 = _tempArray.length ? [_tempMenu] : [];
        }
      } catch (error) {

      }
    },
    async getCostSummaryMenuTree(params) {
      try {
        const result = await getCostSummaryMenuTreeApi(params);
        if (result.code == 200 && result.data instanceof Array) {
          if(this.projectDetailInfo.cbStage === 3 && this.currentCategory === 1){
            if(result.data.length === 0){
              this.currentCategory=2;
              this.categoryList[0].disabled=true;
              const { projectId, cbStage } = this.comProjectDetailInfo;
              const params = {
                projectId,
                cbStage,
                cbType: this.currentCategory
              };
              this.getMenuTree(params);
              return this.init(this.comProjectDetailInfo);
            }
          }
          if(result.data.length === 0){
            this.show=true;
          }
          const _tempArray = result.data;
          const _tempMenu = {
            id: 0,
            cbName: this.currentCategory == 1 ? "成本汇总" : "房建类成本科目",
            children: _tempArray
          };
          this.menuTreeList = _tempArray.length ? [_tempMenu] : [];
          this.init(this.comProjectDetailInfo);
        }
      } catch (error) {

      }
    },
    async getCostSummaryMonthList(params, saveReset = false) {
      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 = saveReset ? this.expenseDate : _now;
          // 默认以当前月数据为准 若不包含当前月 需要手动push数据
          if (!data.find(item => item.expenseDate == _now)) {
            data.push({
              label: dayjs(_now).format("YYYY年MM月"),
              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) {

      }
    },
    // 获得已锁定锁定成本月
    async getLockMonthList(params) {
      try {
        const lockMonth = await getLockMonthListApi(params);
        if (lockMonth.code == 200 && lockMonth.data instanceof Array) {
          this.lockMonthList = lockMonth.data;
        }
      } 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 getCostSummaryAllListApi(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;
          //   });
          // }
          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);
      }
    },
    // 将需要编辑的值 设置为默认值 0
    setEditPropDefaultValue(list = [], editPropsArray = []) {
      const result = list.map(item => {
        editPropsArray.forEach(prop => {
          if (!item[prop]) {
            item[prop] = 0;
          }
        });
        if (item?.children?.length) {
          this.setEditPropDefaultValue(item?.children, editPropsArray);
        }
        return item;
      });
      return result;
    },
    // 模拟 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(saveReset = false) {
      // 当前需要编辑或者新增的成本年份
      const _selectActualCostTime = this.selectActualCostTime;
      this.editCostMonthSelectDialog = false;
      this.addActualCostEditStatus = false;
      this.selectActualCostTime = "";
      /**
       * 判断 当前需要编辑 或者新增的成本年份是否存在于server返回的month数组中 不存在则删除 该月份 然后 选中当前月
       * 默认本月
      */
      if (!_selectActualCostTime) return;
      if (!this.originMonthList.find(item => item.expenseDate == _selectActualCostTime) && _selectActualCostTime != this.getNowMonth()) {
        const index = this.monthList.findIndex(item => item.expenseDate == _selectActualCostTime);
        if (index != -1 && !saveReset) {
          this.monthList.splice(index, 1);
          this.expenseDate = this.getNowMonth();
        }
      }
    },
    async menuSelect(currentId, currentTemp) {
      this.resetEditStatus();
      this.currentNodeValue = currentId;
      const parentId = currentTemp.parent ? this.getCurrentType(currentTemp.parent) : currentId;
      if (parentId) this.currentParentId = parentId;
      const params = this.createRequestConditions(this.expenseDate);
      this.getCostSummaryList(params);
    },
    // 锁定成本
    async lockCostHandler() {
      try {
        const { cbType, projectId } = this.createRequestConditions();
        const params = {
          expenseDate: this.expenseDate,
          cbType,
          projectId
        };
        const tip = await validateBeforeCostLockApi(params);
        if (tip.code == 200 && tip.data == 500) {
          this.lockCostTipDialogContent = tip.msg;
          this.lockCostTipDialog = true;
          return;
        }
      } catch (error) {

      }
    },
    // 锁定成本弹窗关闭
    lockCostTipDialogClose() {
      this.lockCostTipDialogContent = "";
      this.lockCostTipDialog = false;
    },
    // 确定锁定成本
    async okLock() {
      try {
        const { cbType, projectId } = this.createRequestConditions();
        const params = {
          expenseDate: this.expenseDate,
          cbType,
          projectId
        };
        const lockResult = await setCostLockApi(params);
        if (lockResult.code == 200) {
          this.$message.success("锁定成功");
          this.lockCostTipDialog = false;
          const params = this.createRequestConditions();
          await this.getLockMonthList(params);
        }
        this.resetEditStatus();
      } catch (error) {

      }
    },
    // 导出excel
    async exportExcel() {
      try {
        const { cbType, projectId } = this.createRequestConditions();
        const params = {
          expenseDate: this.expenseDate,
          cbType,
          projectId
        };
        let { data, fileName } = await exportCostLockExcelApi(params);
        if (data && fileName) {
          fileName = fileName.split(";")[1].split("filename=")[1];
          this.$download.saveAs(data, decodeURIComponent(fileName));
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 编辑成本
    editCost() {
      // const _disableMonths = this.monthList.filter(item => item.isLock == true).map(item => item.expenseDate);
      const _disableMonths = cloneDeep(this.lockMonthList);
      this.disableMonths = _disableMonths;
      this.editCostMonthSelectDialog = true;
    },
    dialogStatusChange(flag) {
      this.editCostMonthSelectDialog = false;
      // 重置禁用
      this.disableMonths = [];
    },
    //成本月选择回调
    async timeSelect(selectTime) {
      // 编辑状态
      this.addActualCostEditStatus = true;
      this.selectActualCostTime = selectTime;
      // 判断是否包含 选择的年月 包含则修改 未包含则新增
      const findReslut = this.originMonthList.find(item => item.expenseDate == selectTime) || this.monthList.find(item => item.expenseDate == selectTime);
      const params = this.createRequestConditions();
      if (!findReslut) {
        // 不包含当前所选月 新增数据
        let _temp = JSON.parse(JSON.stringify(this.monthList));
        _temp.push({
          label: dayjs(selectTime).format("YYYY年MM月"),
          expenseDate: selectTime,
          isLock: 0
        });
        _temp = this.monthsSort(_temp);
        // console.log(_temp);
        this.monthList = _temp;
      }
      this.expenseDate = selectTime;
      params["expenseDate"] = selectTime;
      // 获取选中月数据
      await this.getCostSummaryList(params);
      // 将编辑区域移动到视口
      await this.$nextTick();
      await this.editRegionToViewPort();
    },
    // 将编辑区域移动到视口
    async editRegionToViewPort() {
      // 获取编辑列所处位置
      const container = document.querySelector(".el-table__body-wrapper");
      /**
       * @type {HTMLTableCellElement}
      */
      const editElement = container.querySelector(".el-table__row [class *= can-edit-column-]");
      if (editElement) {
        const left = editElement.offsetLeft;
        container.scrollTo({
          behavior: "smooth",
          left,
          top: this.lastScrollTop
        });
        this.lastScrollTop = 0;
      }
    },
    // 成本输入数据限制
    editIptValueRectify(value, row, prop) {
      const reg = /^(?!0\d)(?!0+$)(?!0*\.0*$)\d+(\.\d+)?$/;
      if (reg.test(value)) {
        row[prop] = add(0, value);
      }
    },
    //保存成本
    saveCostModify() {
      this.$refs["costSummaryForm"].validate(async flag => {
        if (flag) {
          // 进行差异化对比
          let resultData = this.differentCompare();
          // 没有差异
          if (!resultData.length) {
            this.resetEditStatus();
            const params = this.createRequestConditions(this.expenseDate);
            await this.getCostSummaryList(params);
            return;
          }
          // 有差异数据 记录滚动条滚动位置
          await this.getLastScrollTop();
          const result = await saveCostModifyApi(resultData);
          if (result.code == 200) {
            this.$message.success("保存成功");
            await this.init(this.comProjectDetailInfo, this.expenseDate, true);
            await this.$nextTick();
            await this.editRegionToViewPort();
          }
        }
      });
    },
    //获取竖向滚动条最后的位置
    async getLastScrollTop() {
      const table = document.querySelector(".custom-table .el-table__body-wrapper");
      if (table) {
        this.lastScrollTop = table.scrollTop;
      }
    },
    // 差异化比对
    differentCompare() {
      const originData = this.originTableDataList;
      /**
       * @type {Array<object>}
      */
      let data = cloneDeep(this.dataForm.tableDataList);
      // 差异数据
      const different = this.getDeepDifferentData(data, originData);
      return cloneDeep(different);
    },
    // 深度差异化对比
    getDeepDifferentData(data = [], originData = [], tempArray = []) {
      const len = data.length;
      for (let index = 0; index < len; index++) {
        const item = data[index];
        // 源数据
        const originItem = originData[index];
        // 查看可编辑字段是否存在任意一处 数据不同
        const hasDifferent = editPropNames.some(prop => {
          // 两个皆为无效值 返回false
          if (!parseFloat(item[prop]) && !parseFloat(originItem[prop])) return false;
          return item[prop] != originItem[prop];
        });
        // 浅层级
        if (hasDifferent) {
          tempArray.push({
            id: item.actualId,
            cbSummaryId: item.id,
            taxInclusiveExpense: item.taxInclusiveExpense ? item.taxInclusiveExpense : 0,
            taxExclusiveExpense: item.taxExclusiveExpense ? item.taxExclusiveExpense : 0,
            expenseDate: this.expenseDate
          });
        }
        // 递归深层级
        if (item?.children?.length) {
          this.getDeepDifferentData(item.children, originItem.children, tempArray);
        }
      }
      return tempArray;
    },
    // 获取当前树形结构下 输入框prop的完整路径
    getTableTreeProp(dataList = [], rowId, pathArray = []) {
      const len = dataList.length;
      for (let index = 0; index < len; index++) {
        const item = dataList[index];
        // 返回所在下标index
        if (item.id === rowId) {
          return [...pathArray, index].join("");
        }
        if (item?.children?.length) {
          const childPath = [...pathArray, index, '.children.'];
          const result = this.getTableTreeProp(item.children, rowId, childPath);
          if (result) {
            return result;
          }
        }
      }
      return null;
    },
  },
};
</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;
      margin: 0;

      &: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;

          .lock-cost-btn,
          .export-excel-btn,
          .edit-cost-btn {
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0px 16px;
            background-color: #0081ff;
            border-color: #0081ff;
            border-radius: 4px;
            color: #fff;
            font-size: 14px;
            font-weight: 350;
            margin-right: 16px;
            cursor: pointer;
          }

          .lock-cost-btn {
            /* 当前月锁定 */
            &.current-month-lock {
              cursor: not-allowed;
              background: #66b3ff;
            }
          }

          .edit-cost-btn {
            margin-right: 0px;
          }

          .edit-cost-btn,
          .export-excel-btn {
            &.btn-is-disable {
              cursor: not-allowed;
              background: #66b3ff;
            }
          }
        }
      }

      .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);
            }
          }
        }
      }
    }
  }

  .no-data {
    font-size: 14px;
    font-family: Microsoft YaHei-Regular, Microsoft YaHei;
    font-weight: 400;
    color: #999999;
    text-shadow: 0px 0px 10px rgba(0, 37, 106, 0.10000000149011612);
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #ffffff;
    border-radius: 0px 0px 0px 0px;
    opacity: 1;
    border: 1px solid #eeeeee;
    .no-data-box {
      display: flex;
      flex-direction: column;
      align-items: center;
      img {
        width: 64px;
        height: 79px;
        margin-bottom: 16px;
      }
    }
  }
}
</style>
