<template>
  <div class="feed-summary-container">
    <div v-if="!show" class="feed-summary-inner">
      <div class="left-side-menu">
        <project-side-menu ref="projectSideMenu" :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-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>
            <el-select v-model="isOutPlanCostCombinedPrice" placeholder="成本控制情况" class="project-month-select-options" @change="priceChange" clearable style="margin-left: 16px;">
              <el-option label="超出计划成本" value="超出计划成本"></el-option>
              <el-option label="未超出计划成本" 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="isEntityMaterials">单位换算</el-button>
            <!-- 填写实际成本 -->
            <el-button type="primary" size="medium" class="actual-cost-btn" v-else
              @click="addActualCostEditStatus ? saveActualCost() : fillActualCost()">{{addActualCostEditStatus ? '保存成本' : '填写实际成本'}}</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>
          <!-- 非实体工程材料列表 -->
          <el-form :model="dataForm" ref="feedSummaryForm" :show-message="false" v-else-if="!isEntityMaterials" class="feed-summary-form">
            <custom-table :tableData="dataForm.tableDataList" :formColum="formColum" :max-height="true" :tableDataTotal="total" :paging="false" v-if="total > 0 && !tableLoading"
                          :header-cell-class-name="headerCellClassName" :cell-class-name="cellClassName">
              <template slot="action-field-bar" slot-scope="scope">
                <div class="project-action-field-bar" v-if="rowCanEditInput(scope.rowIndex,hasTarget)">
                  <span class="push-project-use" @click="!rowHasLastPush(scope.rowIndex) ? pushProjectUse(scope.row) :''" :class="{'is-emty-quantities' : rowHasLastPush(scope.rowIndex)}">修改本月差值</span>
                </div>
                <!--<div class="project-action-field-bar" v-if="rowCanEditInput(scope.rowIndex,hasTarget)">-->
                  <!--<span class="push-project-use" :class="{'is-emty-quantities' : rowHasLastPush(scope.rowIndex)}"-->
                    <!--@click="!rowHasLastPush(scope.rowIndex) ? pushProjectUse(scope.row) : ''">修改工程量</span>-->
                <!--</div>-->
                <!--<span v-else>-</span>-->
              </template>
              <template slot="guidePrice" slot-scope="scope">
                {{$decimalFormat(scope.row.guidePrice)}}
              </template>
              <template slot="bidUnitPrice" slot-scope="scope">
                {{$decimalFormat(scope.row.bidUnitPrice)}}
              </template>
              <template slot="unitPriceDifference" slot-scope="scope">
                {{$decimalFormat(scope.row.unitPriceDifference)}}
              </template>
              <template slot="quantity" slot-scope="scope">
                {{$decimalFormat(scope.row.quantity)}}
              </template>
              <template slot="combinedPrice" slot-scope="scope">
                {{$decimalFormat(scope.row.combinedPrice)}}
              </template>
              <template slot="combinedPriceTax" slot-scope="scope">
                {{$decimalFormat(scope.row.combinedPriceTax)}}
              </template>
              <template slot="totalQuantities" slot-scope="scope">
                {{$decimalFormat(scope.row.totalQuantities)}}
              </template>
              <template slot="pushQuantities" slot-scope="scope">
                {{$decimalFormat(scope.row.pushQuantities)}}
              </template>
              <template slot="actualCombinedPrice" slot-scope="scope">
                <div v-if="scope.row.isActualGreaterThanPlan" style="color:#FF204E;">{{$decimalFormat(scope.row.actualCombinedPrice)}}</div>
                <div v-else>{{$decimalFormat(scope.row.actualCombinedPrice)}}</div>
              </template>
              <!-- 本月工程量 -->
              <template slot="quantities" slot-scope="scope">
                <!-- 编辑单元格 -->
                <el-form-item :prop="`tableDataList.${scope.rowIndex}.quantities`" :rules="checkRules.amountCheck"
                  v-if="rowCanEditInput(scope.rowIndex,hasTarget) && addActualCostEditStatus" class="inner-edit-input-item">
                  <el-input placeholder="请输入" v-model="scope.row.quantities" clearable
                    @input="v => statisticsSum(v,'quantities',scope.row)"></el-input>
                </el-form-item>
                <div v-else-if="!addActualCostEditStatus">
                  <div v-if="scope.row.pushQuantities" style="color:#FF204E;">{{$decimalFormat(scope.row.quantities)}}</div>
                  <div v-else>{{$decimalFormat(scope.row.quantities)}}</div>
                </div>
              </template>
              <!-- 本月采购单价 -->
              <template slot="purchaseUnitPrice" slot-scope="scope">
                <!-- 编辑单元格 -->
                <el-form-item :prop="`tableDataList.${scope.rowIndex}.purchaseUnitPrice`" :rules="checkRules.amountCheck"
                  v-if="rowCanEditInput(scope.rowIndex,hasTarget) && addActualCostEditStatus" class="inner-edit-input-item">
                  <el-input placeholder="请输入" v-model="scope.row.purchaseUnitPrice" clearable
                    @input="v => statisticsSum(v,'purchaseUnitPrice',scope.row)"></el-input>
                </el-form-item>
                <span v-else-if="!addActualCostEditStatus">{{$decimalFormat(scope.row.purchaseUnitPrice)}}</span>
              </template>
            </custom-table>
          </el-form>

          <!-- 实体工程材料列表 -->
          <entity-materials-table v-else-if="isEntityMaterials" :tableData="dataForm.tableDataList" :formColum="entityMaterialsFormColum"
            :max-height="true" :tableDataTotal="total" :paging="false" @selectionChange="selectionChange">
            <template slot="action-field-bar" slot-scope="scope">
              <div class="project-action-field-bar">
                <span class="push-project-use" :class="{'is-emty-quantities' : !parseFloat(scope.row.quantities)}"
                  @click="parseFloat(scope.row.quantities) ? pushProjectUse(scope.row) : ''">推送物资</span>
              </div>
            </template>
            <template slot="guidePrice" slot-scope="scope">
              {{$decimalFormat(scope.row.guidePrice)}}
            </template>
            <template slot="bidUnitPrice" slot-scope="scope">
              {{$decimalFormat(scope.row.bidUnitPrice)}}
            </template>
            <template slot="unitPriceDifference" slot-scope="scope">
              {{$decimalFormat(scope.row.unitPriceDifference)}}
            </template>
            <template slot="quantity" slot-scope="scope">
              {{$decimalFormat(scope.row.quantity)}}
            </template>
            <template slot="combinedPrice" slot-scope="scope">
              {{$decimalFormat(scope.row.combinedPrice)}}
            </template>
            <template slot="combinedPriceTax" slot-scope="scope">
              {{$decimalFormat(scope.row.combinedPriceTax)}}
            </template>
            <template slot="totalQuantities" slot-scope="scope">
              {{$decimalFormat(scope.row.totalQuantities)}}
            </template>
            <template slot="conversionQuantities" slot-scope="scope">
              {{$decimalFormat(scope.row.conversionQuantities)}}
            </template>
          </entity-materials-table>

        </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>

    <!-- 填写实际成本触发 -->
    <add-actual-cost v-model="showAddActualCost" :project-create-time="projectDetailInfo.createTime" @timeSelect="timeSelect"></add-actual-cost>

    <!-- 推送工程量 ， 推送物资 -->
    <push-project-use-dialog v-model="pushProjectUseDialog" :is-entity-materials="isEntityMaterials" :row-data="pushProjectUseTemp"
      @dialogClose="dialogClose" @submitPushData="submitPushData"></push-project-use-dialog>

    <edit-Dialog v-model="editDialog" :row-data="pushProjectUseTemp"
      @dialogClose="editDialogClose" @submitEditData="submitEditData"></edit-Dialog>

    <!-- 单位换算弹窗 -->
    <unit-conversion v-if="showUnitConversion" :isVisible="showUnitConversion" :dataList="unitConversionList"
      @refresh="handleDialogVisible()"></unit-conversion>

  </div>
</template>
<script>
import ProjectSideMenu from "@/views/projectCostLedger/detail/components/ProjectSideMenu";
import { getFeedSummaryMenuTreeApi, getFeedSummaryMonthListApi, getFeedSummaryListApi, getFeedSummaryConversionNotice, updateFeedSummaryRowsApi, pushFeedSummaryRowsApi,editEngineeringQuantityApi } from "@/api/projectCostLedger";
import DskTableHeaderSetting from "@/components/DskTableHeaderSetting";
import DskSkeleton from "@/components/DskSkeleton";
import CustomTable from "@/components/CustomTable";
import EntityMaterialsTable from "@/components/CustomTable";
import AddActualCost from "./components/AddActualCost";
import unitConversion from "./components/unitConversion";
import PushProjectUseDialog from "./components/PushProjectUseDialog";
import editDialog from "./components/editDialog";
import { v4 } from 'uuid';
import dayjs from "dayjs";
import { cloneDeep } from "lodash-es";
import { add } from "@/utils/decimal";

// 需要统计的字段名
const statisticsPropNames = [
  "guidePrice",
  "bidUnitPrice",
  "unitPriceDifference",
  "quantity",
  "combinedPrice",
  "combinedPriceTax",
  "quantities",
  "totalQuantities",
  "purchaseUnitPrice"
];

// 可编辑字段
const editPropNames = [
  "quantities",
  "purchaseUnitPrice",
];

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;
      }
    },
    recordDate: {
      handler(newValue, oldValue) {
        this.oldRecordDate = newValue;
      }
    }
  },
  components: {
    ProjectSideMenu,
    DskTableHeaderSetting,
    CustomTable,
    EntityMaterialsTable,
    DskSkeleton,
    AddActualCost,
    unitConversion,
    PushProjectUseDialog,
    editDialog
  },
  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"),
      show:false,
      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: true, uid: v4() },
        { label: '成本科目', prop: "cbSubjectName", width: "137", uid: v4(), fixed: true },
        { label: '名称', prop: "cbName", width: "232", uid: v4(), fixed: true },
        { label: '公司编码', prop: "companyNo", width: "137", uid: v4() },
        { label: '集团编码', prop: "orgNo", width: "137", 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", align: "center", uid: v4(), children: [
            { label: '指导价格', prop: "guidePrice", minWidth: "81", uid: v4(), slot: true },
            { label: '投标选用单价（不含税）', prop: "bidUnitPrice", minWidth: "179", uid: v4(), slot: true },
            { label: '单价差额', prop: "unitPriceDifference", minWidth: "81", uid: v4(), slot: true },
            { label: '数量', prop: "quantity", minWidth: "150", uid: v4(), slot: true },
            { label: '合价（不含税）', prop: "combinedPrice", minWidth: "150", uid: v4(), slot: true },
            { label: '合价（含税）', prop: "combinedPriceTax", minWidth: "150", uid: v4(), slot: true },
            { label: '品牌名称', prop: "brandName", minWidth: "81", uid: v4() },
            { label: '投标选用来源', prop: "bidSource", minWidth: "109", uid: v4() },
          ]
        },
        {
          label: '实际成本', prop: "sjcb", align: "center", uid: v4(), children: [
            { label: 'IPM本月工程量', prop: "quantities", minWidth: "160", uid: v4(), slot: true },
            { label: '截止本月工程量', prop: "totalQuantities", minWidth: "160", uid: v4(), slot: true },
            { label: '本月采购单价', prop: "purchaseUnitPrice", minWidth: "160", uid: v4(), slot: true },
            { label: '合价（不含税）', prop: "actualCombinedPrice", minWidth: "150", uid: v4(), slot: true },
            { label: '填写时间', prop: "createTime", minWidth: "160", uid: v4(), slot: true },
          ]
        },
        { label: '本月差值', prop: "pushQuantities", width: "110", uid: v4(), slot: true },
        { label: '累计差值', prop: "cumulativeDifference", width: "110", uid: v4(), slot: true },
        { label: '备注', prop: "remark", width: "115", uid: v4(), slot: true },
        { label: '操作', prop: "action-field-bar", width: "120", uid: v4(), fixed: "right" },
      ],
      // 实体工程材料表头
      entityMaterialsFormColum: [
        { label: '多选', prop: "staticSerialNumber", type: "selection", lock: true, width: "53", fixed: "left", uid: v4() },
        { label: '序号', prop: "staticIndexNumber", type: "index", lock: true, width: "53", fixed: "left", uid: v4() },
        { label: '成本科目', prop: "cbSubjectName", width: "137", uid: v4(), fixed: "left" },
        { label: '名称', prop: "cbName", width: "232", uid: v4(), fixed: "left" },
        { label: '公司编码', prop: "companyNo", width: "137", uid: v4() },
        { label: '集团编码', prop: "orgNo", width: "137", 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", align: "center", uid: v4(), children: [
            { label: '指导价格', prop: "guidePrice", minWidth: "81", uid: v4(), slot: true },
            { label: '投标选用单价（不含税）', prop: "bidUnitPrice", minWidth: "179", uid: v4(), slot: true },
            { label: '单价差额', prop: "unitPriceDifference", minWidth: "81", uid: v4(), slot: true },
            { label: '数量', prop: "quantity", minWidth: "150", uid: v4(), slot: true },
            { label: '合价（不含税）', prop: "combinedPrice", minWidth: "150", uid: v4(), slot: true },
            { label: '合价（含税）', prop: "combinedPriceTax", minWidth: "150", uid: v4(), slot: true },
            { label: '品牌名称', prop: "brandName", minWidth: "81", uid: v4() },
            { label: '投标选用来源', prop: "bidSource", minWidth: "109", uid: v4() },
          ]
        },
        {
          label: '实际成本', prop: "sjcb", align: "center", uid: v4(), children: [
            { label: '物料验收系统本月总量', prop: "quantities", minWidth: "180", uid: v4(), slot: true },
            { label: '换算后本月总量', prop: "conversionQuantities", minWidth: "160", uid: v4(), slot: true },
            { label: '截至本月总用量', prop: "totalQuantities", minWidth: "160", uid: v4(), slot: true },
            { label: '剩余物料', prop: "sss", minWidth: "160", uid: v4(), slot: true },
            { label: '填写时间', prop: "createTime", minWidth: "160", uid: v4(), slot: true },
          ]
        },
        { label: '操作', prop: "action-field-bar", width: "140", uid: v4(), fixed: "right" },
      ],
      // 已记录月份集合
      monthList: [],
      // 源数据月份
      originMonthList: [],
      // 当前查询的数据月份
      recordDate: "",
      // 历史查询月份
      oldRecordDate: "",
      //是否超出计划成本合价
      isOutPlanCostCombinedPrice:'',
      // 当前选中子菜单的父类名称
      currentParentName: "",
      // 当前选中的成本科目
      currentNodeName: "",
      // 数据列表
      originTableDataList: [],
      dataForm: {
        // 数据列表源数据
        tableDataList: [],
      },
      statisticsParentName: ["劳务分包工程", "专业分包工程"],
      // 填写实际成本弹窗
      showAddActualCost: false,
      // 填写实际成本 编辑状态
      addActualCostEditStatus: false,
      // 当前选择的成本年份
      selectActualCostTime: "",
      lastScrollTop: 0,
      // 推送工程量弹窗
      pushProjectUseDialog: false,
      //修改本月差值弹窗
      editDialog: false,
      // 修改本月差值数据缓存
      pushProjectUseTemp: {
        id: "",
        pushQuantities: "",
        cbSubjectName: "",
        cbName: "",
        companyNo: "",
        quantities: "",
        projectName: "",
      },
      checkRules: {
        amountCheck: [
          { trigger: ["change"], validator: amountCheckValidator }
        ]
      },
      statisticsTimer: null,
      // 单位换算弹窗
      showUnitConversion: false,
      //单位换算数据
      unitConversionList: []
    };
  },
  //可访问data属性
  created() {
    this.init(this.comProjectDetailInfo);
  },
  beforeDestroy() {
    this.clearStatisticsTimer();
  },
  //计算集
  computed: {
    hasTarget() {
      return this.statisticsParentName.includes(this.currentParentName);
    },
    // 实体工程材料
    isEntityMaterials() {
      return this.currentParentName.indexOf('实体工程材料') != -1;
    }
  },
  //方法集
  methods: {
    async init(detail = {}, resetDate = "", saveReset = false) {
      try {
        this.resetEditStatus(saveReset);
        const { projectId, cbStage } = detail;
        if (!projectId) return;
        const params = {
          projectId,
          cbStage
        };
        await this.getFeedSummaryMenuTree(params);
        await this.getFeedSummaryMonthList(params, saveReset);
        await this.initDefaultSetting(resetDate, saveReset);
      } catch (error) {
        console.log(error);
      } finally {
        this.tableLoading = false;
      }
    },
    async initDefaultSetting(resetDate = "", saveReset = false) {
      try {
        await this.$nextTick();
        const menus = this.$refs["projectSideMenu"].getResultMenuList();
        const defaultCurrent = this.findMenuNode(menus, saveReset ? this.currentNodeName : "结构劳务分包");
        // 默认选中结构劳务分包
        if (defaultCurrent) {
          this.currentNodeName = defaultCurrent.nodeName;
          const parentName = defaultCurrent.parent ? this.getCurrentType(defaultCurrent.parent) : defaultCurrent.name;
          if (parentName) this.currentParentName = parentName;
          const params = this.createRequestConditions(resetDate);
          await this.getFeedSummaryList(params);
        }
      } catch (error) {
        console.log(error);
      }
    },
    getNowMonth() {
      return dayjs(new Date().valueOf()).format("YYYYMM");
    },
    createRequestConditions(resetDate = "") {
      const { projectId, cbStage } = this.comProjectDetailInfo;
      const params = {
        projectId,
        cbStage
      };
      params["cbSubjectName"] = this.currentNodeName;
      // 判断当月是否存在于server返回month集合中 有传入的重置时间 采用重置时间
      const _now = this.getNowMonth();
      if (resetDate && this.includeNowMonth(resetDate)) {
        params["recordDate"] = resetDate;
      } else if (this.includeNowMonth(_now)) {
        params["recordDate"] = _now;
      }
      return params;
    },
    // 返回当前月是否在server month集合中
    includeNowMonth(time) {
      return this.originMonthList.includes(time);
    },
    findMenuNode(tree, nodeName, targetName = "nodeName") {
      for (const item of tree) {
        if (item[targetName] == nodeName) return item;
        if (item.children instanceof Array) {
          const result = this.findMenuNode(item.children, nodeName, targetName);
          if (result) return result;
        }
      }
    },
    async getFeedSummaryList(params = {}) {
      try {
        this.tableLoading = true;
        const list = await getFeedSummaryListApi(params);
        if (list.code == 200 && list.data instanceof Array) {
          const _temp = list.data;
          // 计算总和
          // if (this.hasTarget && _temp.length) {
          if (_temp.length) {
            const row = this.countRowParams(_temp, statisticsPropNames);
            _temp.unshift(row);
          }
          this.$set(this.dataForm, "tableDataList", cloneDeep(_temp));
          this.originTableDataList = cloneDeep(_temp);
          this.total = _temp.length;
        }
      } catch (error) {
        console.log(error);
      } finally {
        this.tableLoading = false;
      }
    },
    countRowParams(arraylist = [], _statisticsPropNames) {
      if (arraylist.length) {
        const _template = {};
        const _temp = cloneDeep(arraylist[0]);
        const keys = Object.keys(_temp);
        // 映射key
        for (const key of keys) {
          if (key == "id") {
            _template[key] = "0";
            continue;
          } else if (key == "cbSubjectName") {
            _template[key] = "合计";
            continue;
          }
          _template[key] = "";
        }
        // 循环统计 需要统计的列 总数
        for (const prop of _statisticsPropNames) {
          const sum = this.sumHandler(arraylist, prop);
          // 对应key 赋值结果
          _template[prop] = sum;
        }

        return _template;
      }
    },
    async getFeedSummaryMenuTree(params) {
      try {
        const result = await getFeedSummaryMenuTreeApi(params);
        if(result.data.length === 0){
          this.show=true;
        }
        if (result.code == 200 && result.data instanceof Array) {
          const _tempArray = result.data;
          this.menuTreeList = _tempArray;
        }
      } catch (error) {

      }
    },
    async getFeedSummaryMonthList(params, saveReset = false) {
      try {
        const monthList = await getFeedSummaryMonthListApi(params);
        if (monthList.code == 200 && monthList.data instanceof Array) {
          const data = monthList.data;
          this.originMonthList = cloneDeep(data);
          const _now = this.getNowMonth();
          this.recordDate = saveReset ? 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.resetEditStatus();
      // 获取列表数据
      this.getFeedSummaryList(params);
    },
    priceChange(value){
      // 请求列表参数
      const params = this.createRequestConditions();
      if(value){
        params["isOutPlanCostCombinedPrice"] = this.isOutPlanCostCombinedPrice === '超出计划成本' ? true : false;
      }
      // 获取列表数据
      this.getFeedSummaryList(params);
    },
    async menuSelect(currentId, currentTemp) {
      this.resetEditStatus();
      this.currentNodeName = currentId;
      const parentName = currentTemp.parent ? this.getCurrentType(currentTemp.parent) : currentId;
      if (parentName) this.currentParentName = parentName;
      this.resetTableData();
      //  实体工程材料
      const params = this.createRequestConditions(this.recordDate);
      await this.getFeedSummaryList(params);
      if (this.isEntityMaterials) {
        this.getFeedSummaryConversionNotice(params);
      }
    },
    async getFeedSummaryConversionNotice(params) {
      const data = await getFeedSummaryConversionNotice(params);
      // const data = {
      //   "code": 200,
      //   "msg": "系统检测到您近期未进行物料单位换算，请立即进行换算。",
      //   "data": [
      //     {
      //       "id": "1763389258189500519",
      //       "cbSubjectName": "钢筋",
      //       "companyNo": "FG-002-010025",
      //       "orgNo": "",
      //       "cbName": "热轧带肋钢筋HRB400E",
      //       "jobContent": "20mm  定尺12m",
      //       "calculationRule": "",
      //       "unit": "吨",
      //       "materialDescription": "",
      //       "guidePrice": "",
      //       "bidUnitPrice": 3513.27,
      //       "unitPriceDifference": null,
      //       "quantity": 0.317,
      //       "combinedPrice": 1113.70659,
      //       "combinedPriceTax": 1115.154424,
      //       "brandName": "",
      //       "bidSource": "请在此处填写",
      //       "remark": "",
      //       "quantities": 123123.0,
      //       "quantitiesUnit": "T",
      //       "conversionQuantities": null,
      //       "conversionUnit": null,
      //       "purchaseUnitPrice": null,
      //       "createTime": "2024-03-05 16:55:54",
      //       "totalQuantities": null,
      //       "actualId": "11111111",
      //       "pushQuantities": null,
      //       "ipmProjectCode": null,
      //       "ipmContractCode": null,
      //       "ipmJobCode": null
      //     }
      //   ]
      // };
      if (data.data) {
        this.$confirm('系统检测到您近一月未进行物料单位换算，是否立即进行换算？', '温馨提示', {
          confirmButtonText: '立即换算',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.unitConversionList = data.data;
          this.showUnitConversion = true;
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消换算'
          });
        });
      } else if (data.data instanceof Array) {
        const _temp = data.data;
        this.$set(this.dataForm, "tableDataList", cloneDeep(_temp));
        this.originTableDataList = cloneDeep(_temp);
        this.total = _temp.length;
      }
    },
    // 复选框回调
    selectionChange(array) {

    },
    getCurrentType(parent) {
      if (parent.level == 2) {
        return parent.nodeName;
      }
      if (parent.parent) {
        return this.getCurrentType(parent.parent);
      }
    },
    // 表头设置变化
    async settingChange(use) {
      try {
        this.formColum = use;
      } catch (error) {

      }
    },
    // 填写或修改新的 成本月份
    fillActualCost() {
      this.showAddActualCost = true;
    },
    clearStatisticsTimer() {
      clearTimeout(this.statisticsTimer);
      this.statisticsTimer = null;
    },
    // 实时统计
    statisticsSum(value, prop, row) {
      this.clearStatisticsTimer();
      const reg = /^(?!0\d)(?!0+$)(?!0*\.0*$)\d+(\.\d+)?$/;
      if (reg.test(value)) {
        row[prop] = add(0, value);
      }
      // 填写一秒后触发
      this.statisticsTimer = setTimeout(() => {
        const sum = this.sumHandler(this.dataForm.tableDataList, prop, this.hasTarget);
        // 更新统计值
        this.$set(this.dataForm.tableDataList[0], prop, sum);
      }, 500);
    },
    sumHandler(dataList, prop, hasTotal = false) {
      const reg = /^(?!0\d)(?!0*\.0*$)\d+(\.\d+)?$/;
      const sum = dataList.reduce((pre, current, index) => {
        if (hasTotal && index == 0) return 0;
        const before = Object.prototype.toString.call(pre) == "[object Object]" ? reg.test(pre[prop]) ? pre[prop] : 0 : parseFloat(pre) ? pre : 0;
        const after = Object.prototype.toString.call(current) == "[object Object]" ? reg.test(current[prop]) ? current[prop] : 0 : parseFloat(current) ? current : 0;
        return add(before, after);
      }, 0);
      return sum;
    },
    // // 当前行是否可编辑
    rowCanEditInput(index, hasTarget) {
      // 不为id 0 或 不是劳务分包跟专业分包
      return index != 0 || !hasTarget;
    },
    // 当前行源数据是否存在以推送工程量
    rowHasLastPush(index) {
      const _tempRow = this.originTableDataList[index];
      return !parseFloat(_tempRow.quantities);
    },
    // 保存
    saveActualCost() {
      this.$refs["feedSummaryForm"].validate(async flag => {
        if (flag) {
          // 进行差异化对比
          let resultData = this.differentCompare();
          console.log(resultData, "差异数据");
          if (!resultData.length) {
            this.resetEditStatus();
            const params = this.createRequestConditions();
            await this.getFeedSummaryList(params);
            return;
          }
          // 有差异提交数据
          resultData = resultData.map(item => {
            return {
              id: item.actualId,
              cbQuantitySummaryId: item.id,
              quantities: item.quantities ? item.quantities : 0,
              purchaseUnitPrice: item.purchaseUnitPrice ? item.purchaseUnitPrice : 0,
              recordDate: this.recordDate
            };
          });
          // 有差异数据 记录滚动条滚动位置
          await this.getLastScrollTop();
          const result = await updateFeedSummaryRowsApi(resultData);
          if (result.code == 200) {
            this.$message.success("保存成功");
            await this.init(this.comProjectDetailInfo, this.recordDate, 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;
      }
    },
    // 修改工程用量
    pushProjectUse(row) {
      if (!row.actualId) return;
      // 打开推送推送弹窗
      const _temp = {
        ...this.pushProjectUseTemp, ...{
          id: row.actualId,
          projectName: this.projectDetailInfo.projectName,
          cbSubjectName: row.cbSubjectName,
          cbName: row.cbName,
          companyNo: row.companyNo,
          quantities: row.quantities,
          pushQuantities: '',
        }
      };
      this.pushProjectUseTemp = _temp;
      // this.pushProjectUseDialog = true;
      this.editDialog = true;
    },
    // 推送工程用量弹窗关闭
    dialogClose() {
      this.pushProjectUseTemp = this.$options.data.call(this).pushProjectUseTemp;
    },
    // 确定推送
    async submitPushData(pushForm) {
      try {
        const result = await pushFeedSummaryRowsApi(pushForm);
      } catch (error) {

      }
    },
    // 修改工程用量弹窗关闭
    editDialogClose() {
      this.editDialog = this.$options.data.call(this).pushProjectUseTemp;
    },
    // 确定修改
    async submitEditData(pushForm) {
      try {
        const result = await editEngineeringQuantityApi(pushForm);
        if(result.code === 200){
          this.editDialog=false;
          this.init(this.comProjectDetailInfo);
        }
      } catch (error) {

      }
    },
    differentCompare() {
      const originData = this.originTableDataList;
      /**
       * @type {Array<object>}
      */
      let data = cloneDeep(this.dataForm.tableDataList);
      const different = data.filter((item, index) => {
        if (index == 0 && this.hasTarget) return false;
        const flag = editPropNames.some(prop => {
          // 两个皆为无效值 返回false
          if (!parseFloat(item[prop]) && !parseFloat(originData[index][prop])) return false;
          return item[prop] != originData[index][prop];
        });
        return flag;
      });
      return cloneDeep(different);
    },
    // 编辑状态下 进行了其它操作
    resetEditStatus(saveReset = false) {
      // 当前需要编辑或者新增的成本年份
      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 && !saveReset) {
          this.monthList.splice(index, 1);
          this.recordDate = this.getNowMonth();
        }
      }
    },
    // 重置表格数据
    resetTableData() {
      this.$set(this.dataForm, "tableDataList", []);
      this.originTableDataList = [];
      this.total = 0;
    },
    async timeSelect(selectTime) {
      // 编辑状态
      this.addActualCostEditStatus = true;
      this.selectActualCostTime = selectTime;
      // 判断是否包含 选择的年月 包含则修改 未包含则新增
      const findReslut = this.originMonthList.includes(selectTime) || this.monthList.find(item => item.value == selectTime);
      const params = this.createRequestConditions();
      if (!findReslut) {
        // 不包含当前所选月 新增数据
        let _temp = JSON.parse(JSON.stringify(this.monthList));
        _temp.push({
          label: dayjs(selectTime).format("YYYY年MM月"),
          value: selectTime
        });
        _temp = this.monthsSort(_temp);
        // console.log(_temp);
        this.monthList = _temp;
      }
      this.recordDate = selectTime;
      params["recordDate"] = selectTime;
      // 获取选中月数据
      await this.getFeedSummaryList(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;
      }
    },
    cellClassName({ row, column, rowIndex, columnIndex }) {
      const { property } = column;
      // let arr = ['sjcb','quantities','totalQuantities','purchaseUnitPrice','createTime']
      // if(arr.includes(column.property)){
      //   return 'tored'
      // }else
      if (editPropNames.includes(property)) {
        return `can-edit-column-${property}`;
      }
      return "";
    },
    headerCellClassName({column}){
      // let arr = ['sjcb','quantities','totalQuantities','purchaseUnitPrice','createTime']
      // if(arr.includes(column.property)){
      //   return 'tored'
      // }
    },
    //关闭单位换算弹窗
    handleDialogVisible() {
      this.showUnitConversion = false;
    },
  },
}
</script>
<style lang="scss" scoped>
.feed-summary-container {
  width: 100%;
  height: 100%;

  ::v-deep .tored{
    background: rgb(255,236,236) !important;
  }
  .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-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;
              }
              .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>
