<template>
  <div class="field-expenses-container">
    <div class="field-expenses-inner">
      <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_6.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="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">

          </div>
        </div>
        <!-- 数据列表部分 -->
        <div class="project-feedsummary-list-container">
          <dsk-skeleton v-if="tableLoading"></dsk-skeleton>
          <custom-table v-else-if="!tableLoading" :tableData="dataForm.tableDataList" :formColum="formColum" :max-height="true"
            :tableDataTotal="total" :paging="false">
          </custom-table>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import ProjectSideMenu from "@/views/projectCostLedger/detail/components/ProjectSideMenu";
import { getFieldExpensesMenuTreeApi, getFieldExpensesMonthListApi, getFieldExpensesListApi, getFieldExpensesOtherListApi } from "@/api/projectCostLedger";
import DskSkeleton from "@/components/DskSkeleton";
import CustomTable from "@/components/CustomTable";
import { v4 } from 'uuid';
import dayjs from "dayjs";
import { cloneDeep } from "lodash-es";
export default {
  name: "fieldExpenses",
  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;
      }
    },
    currentNodeName: {
      handler(newValue) {
        const formColum = this.getCurrentFormColumOptions(newValue);
        this.formColum = formColum;
      }
    }
  },
  components: {
    ProjectSideMenu,
    CustomTable,
    DskSkeleton
  },
  data() {
    return {
      menuOptions: {
        nodeName: "menuName",
        nodeValue: "fileId",
      },
      comProjectDetailInfo: this.projectDetailInfo ? cloneDeep(this.projectDetailInfo) : {},
      comProjectId: this.projectId,
      menuTreeList: [],
      // 加载数据列表
      tableLoading: true,
      total: 0,
      // 列表表头
      formColum: [],
      formColumOptions: {
        "现场经费": [
          { label: '名称', prop: "expenseName", minWidth: "175", uid: v4(), showOverflowTooltip: true },
          { label: '数量', prop: "expenseValue", width: "175", uid: v4() },
          { label: '占比', prop: "proportion", width: "175", uid: v4() },
          { label: '本月费用', prop: "byfy", minWidth: "175", uid: v4() },
          { label: '截至本月总费用', prop: "jzbyzfy", minWidth: "175", uid: v4() },
        ],
        "其他费用(包含建设其他费)": [
          { label: '序号', prop: "number", width: "60", fixed: false, uid: v4() },
          { label: '名称', prop: "expenseName", width: "121", uid: v4(), showOverflowTooltip: true },
          { label: '单位', prop: "unit", width: "121", uid: v4() },
          { label: '成本数量', prop: "cbCount", width: "121", uid: v4() },
          { label: '使用时间', prop: "useTime", width: "129", uid: v4() },
          { label: '公司单价', prop: "unitPrice", width: "129", uid: v4() },
          { label: '目标成本合价（不含税）', prop: "excludeTaxSumPrice", width: "180", uid: v4() },
          { label: '目标成本合价（含税）', prop: "includeTaxSumPrice", width: "180", uid: v4() },
          { label: '备注', prop: "remark", width: "384", uid: v4(), showOverflowTooltip: true },
          { label: '成本科目', prop: "cbSubject", width: "129", uid: v4() },
          { label: '税金类型', prop: "taxType", width: "129", uid: v4() },
          { label: '本月费用', prop: "byfy", width: "129", uid: v4() },
          { label: '截止本月总费用', prop: "jzbyzfy", width: "129", uid: v4() },
        ],
        "工资统筹": [
          { label: '序号', prop: "number", width: "60", fixed: false, uid: v4() },
          { label: '名称', prop: "expenseName", minWidth: "121", uid: v4(), showOverflowTooltip: true },
          { label: '单位', prop: "unit", width: "121", uid: v4() },
          { label: '成本数量', prop: "cbCount", width: "121", uid: v4() },
          { label: '使用时间', prop: "useTime", width: "121", uid: v4() },
          { label: '公司单价', prop: "unitPrice", width: "121", uid: v4() },
          { label: '目标成本合价（不含税）', prop: "excludeTaxSumPrice", width: "180", uid: v4() },
          { label: '目标成本合价（含税）', prop: "includeTaxSumPrice", width: "180", uid: v4() },
          { label: '成本科目', prop: "cbSubject", width: "121", uid: v4() },
          { label: '税金类型', prop: "taxType", width: "121", uid: v4() },
          { label: '本月费用', prop: "byfy", width: "121", uid: v4() },
          { label: '截止本月总费用', prop: "jzbyzfy", width: "128", uid: v4() },
        ],
        "现场管理费": [
          { label: '序号', prop: "number", width: "60", fixed: false, uid: v4() },
          { label: '名称', prop: "expenseName", minWidth: "121", uid: v4(), showOverflowTooltip: true },
          { label: '单位', prop: "unit", width: "121", uid: v4() },
          { label: '工程量', prop: "engineeringVolume", width: "121", uid: v4() },
          { label: '增值税税率', prop: "addedTaxRate", width: "121", uid: v4() },
          { label: '不含税单价（元）', prop: "unitPrice", width: "180", uid: v4() },
          { label: '不含税合价（元）', prop: "excludeTaxSumPrice", width: "180", uid: v4() },
          { label: '含税合价（元）', prop: "includeTaxSumPrice", width: "180", uid: v4() },
          { label: '备注', prop: "remark", width: "121", uid: v4() },
          { label: '成本科目', prop: "cbSubject", width: "121", uid: v4() },
          { label: '税金类型', prop: "taxType", width: "121", uid: v4() },
          { label: '本月费用', prop: "byfy", width: "121", uid: v4() },
          { label: '截止本月总费用', prop: "jzbyzfy", width: "128", uid: v4() },
        ]
      },
      // 已记录月份集合
      monthList: [],
      // 源数据月份
      originMonthList: [],
      // 当前查询的数据月份
      recordDate: "",
      // 历史查询月份
      oldRecordDate: "",
      // 当前选中菜单名称
      currentNodeName: "",
      // 当前选中的成本科目
      currentNodeValue: "",
      // 数据列表
      originTableDataList: [],
      dataForm: {
        // 数据列表源数据
        tableDataList: [],
      }
    };
  },
  //可访问data属性
  created() {
    this.init(this.comProjectDetailInfo);
  },
  //计算集
  computed: {

  },
  //方法集
  methods: {
    getCurrentFormColumOptions(currentNodeName) {
      const _temp = this.formColumOptions[currentNodeName] ? cloneDeep(this.formColumOptions[currentNodeName]) : [];
      return _temp;
    },
    async init(detail = {}) {
      try {
        const { projectId, cbStage } = detail;
        if (!projectId) return;
        const params = {
          projectId,
          cbStage
        };
        await this.getFieldExpensesMenuTree(projectId);
        // await this.getFieldExpensesMonthList(params);
        await this.initDefaultSetting();
      } catch (error) {
        console.log(error);
      } finally {
        this.tableLoading = false;
      }
    },
    async initDefaultSetting() {
      try {
        await this.$nextTick();
        const menus = this.$refs["projectSideMenu"].getResultMenuList();
        const defaultCurrent = this.findMenuNode(menus, "现场经费");
        if (defaultCurrent) {
          this.currentNodeValue = defaultCurrent.nodeValue;
          this.currentNodeName = defaultCurrent.nodeName;
          const params = this.createRequestConditions();
          await this.getFieldExpensesList(params);
        }
      } catch (error) {
        console.log(error);
      }
    },
    getNowMonth() {
      return dayjs(new Date().valueOf()).format("YYYYMM");
    },
    createRequestConditions() {
      const { projectId, cbStage } = this.comProjectDetailInfo;
      const params = {
        projectId,
        cbStage
      };
      params["cbSubjectName"] = this.currentNodeValue;
      // 判断当月是否存在于server返回month集合中
      const _now = this.getNowMonth();
      if (this.includeNowMonth(_now)) {
        params["recordDate"] = _now;
      }
      return params;
    },
    // 返回当前月是否在server month集合中
    includeNowMonth(time) {
      return this.originMonthList.includes(time);
    },
    findMenuNode(tree, nodeName, targetName = "nodeName", childName = "children") {
      for (const item of tree) {
        if (item[targetName] == nodeName && !item[childName]?.length) return item;
        if (item.children instanceof Array) {
          const result = this.findMenuNode(item.children, nodeName, targetName, childName);
          if (result) return result;
        }
      }
    },
    async getFieldExpensesList(params = {}) {
      try {
        this.tableLoading = true;
        const list = await getFieldExpensesListApi(params.projectId);
        if (list.code == 200 && list.data instanceof Array) {
          const _temp = list.data;
          this.$set(this.dataForm, "tableDataList", cloneDeep(_temp));
          this.originTableDataList = cloneDeep(_temp);
          this.total = _temp.length;
        }
      } catch (error) {
        console.log(error);
      } finally {
        this.tableLoading = false;
      }
    },
    async getFieldExpensesOtherList(params = {}) {
      try {
        this.tableLoading = true;
        const list = await getFieldExpensesOtherListApi(params);
        if (list.code == 200 && list.data instanceof Array) {
          const _temp = list.data;
          this.$set(this.dataForm, "tableDataList", cloneDeep(_temp));
          this.originTableDataList = cloneDeep(_temp);
          this.total = _temp.length;
        }
      } catch (error) {
        console.log(error);
      } finally {
        this.tableLoading = false;
      }
    },
    async getFieldExpensesMenuTree(projectId) {
      try {
        const result = await getFieldExpensesMenuTreeApi(projectId);
        if (result.code == 200 && result.data instanceof Array) {
          let _tempArray = result.data;
          _tempArray = _tempArray.sort((before, after) => {
            return before["menuLevel"] - after["menuLevel"];
          });
          const _tempMenu = {
            fileId: 0,
            menuName: "现场经费",
            children: _tempArray
          };
          this.menuTreeList = [_tempMenu];
        }
      } catch (error) {
        console.log(error);
      }
    },
    async getFieldExpensesMonthList(params) {
      try {
        const monthList = await getFieldExpensesMonthListApi(params);
        if (monthList.code == 200 && monthList.data instanceof Array) {
          const data = monthList.data;
          this.originMonthList = cloneDeep(data);
          const _now = this.getNowMonth();
          this.recordDate = _now;
          this.oldRecordDate = _now;
          // 默认以当前月数据为准 若不包含当前月 需要手动push数据
          if (!data.includes(_now)) {
            data.push(_now);
          }
          // 年月排序
          let _tempMonthList = this.monthsSort(data);
          _tempMonthList = _tempMonthList.map(item => {
            return {
              label: dayjs(item).format("YYYY年MM月"),
              value: item
            };
          });
          this.monthList = _tempMonthList;
        }
      } catch (error) {

      }
    },
    monthsSort(monthList) {
      const sortResult = monthList.sort((before, after) => {
        const _before = Object.prototype.toString.call(before) == "[object Object]" ? before["value"] : before;
        const _after = Object.prototype.toString.call(before) == "[object Object]" ? after["value"] : after;
        return parseInt(_after) - parseInt(_before);
      });
      return sortResult;
    },
    monthChange(month) {
      // 当前月
      const _now = this.getNowMonth();
      // 请求列表参数
      const params = this.createRequestConditions();
      // 清空了年月默认选中当前月
      if (!month) {
        this.recordDate = _now;
        // 如果命中的旧月份 等于当前月 且 不处于编辑状态 说明清空的是当前月 不调用接口
        if (this.oldRecordDate == _now && !this.addActualCostEditStatus) return;
      } else {
        // 正常选择
        params["recordDate"] = month;
        // 记录历史切换年月
        this.oldRecordDate = month;
      }
      // 获取列表数据
      this.getFieldExpensesList(params);
    },
    async menuSelect(currentId, currentTemp) {
      this.currentNodeValue = currentId;
      const menuName = currentTemp.nodeName;
      this.currentNodeName = menuName;
      // 请求数据列表
      const isDefault = menuName == "现场经费";
      const params = isDefault ? this.createRequestConditions() : {
        projectId: this.comProjectDetailInfo.projectId,
        fileId: currentId
      };
      if (isDefault) {
        this.getFieldExpensesList(params);
      } else {
        this.getFieldExpensesOtherList(params);
      }
    },
    getCurrentType(parent) {
      if (parent.level == 2) {
        return parent.nodeName;
      }
      if (parent.parent) {
        return this.getCurrentType(parent.parent);
      }
    }
  },
}
</script>
<style lang="scss" scoped>
.field-expenses-container {
  width: 100%;
  height: 100%;

  .field-expenses-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-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: hidden;

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

        ::v-deep .table-list-com-ins {
          .table-item {
            .el-table {
              th {
                height: 40px;
              }
              .cell {
                font-size: 14px;
                font-weight: 350;
              }
            }
          }
        }

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

          .push-project {
            color: #0081ff;
            font-size: 14px;
            font-weight: 350;
            cursor: pointer;
          }
        }
      }
    }
  }
}
</style>
