<template>
  <LjDrawer ref="LjDrawerRef" size="80%" :class="prefixCls">
    <template #header>
      <div class="flx-1">
        {{ $t("business.detail.quoteList") }}

        <el-button v-if="iforigin" type="primary" size="small" @click="handleOpenOriginQuote">
          {{ ifShowOrigin ? "返回新报价清单" : "查看旧报价清单" }}
        </el-button>
        <el-checkbox
          v-if="!ifShowOrigin"
          v-model="ifExpandAll"
          label="展开明细"
          size="small"
          style="margin-left: 20px"
          @change="toggleRowExpansionAll()"
        ></el-checkbox>
      </div>
      <div class="flx-shrink">
        <el-button v-if="iforigin" size="small" @click="handleExportExcel"> 导出Excel </el-button>
      </div>
    </template>

    <el-descriptions :column="3">
      <template #title>
        <span class="text-body-b">报价日期：</span>
        <span class="text-body-b" v-if="mainData.data.createtime">{{ isFilterTime(mainData.data.createtime) }}</span>
      </template>
      <template #extra>
        <template v-if="ifShowOrigin">
          <span class="text-body-b">报价金额：</span>
          <span class="text-body-b">{{ isFilterPrice(mainData.data.foreign_cost) + isCurrency }}</span>
        </template>
        <template v-else>
          <div class="flx-end">
            <div class="ml-24" v-for="(itm, idx) in getStaticData" :key="idx">
              <span class="text-body-b">{{ itm.label }}：</span>
              <span class="text-body-b">{{ isFilterPrice(itm.value) }}</span>
            </div>
          </div>
        </template>
      </template>
      <el-descriptions-item v-for="(item, idx) in fields" :key="idx" width="80">
        <template #label>
          <span class="text-secondary-text"> {{ item.label }}: </span>
        </template>
        <span class="text-body-m">{{
          Object.keys(item).includes("value") ? item.value : isFilterPrice(mainData.data[item.field])
        }}</span>
      </el-descriptions-item>
    </el-descriptions>

    <template v-if="!ifShowOrigin">
      <el-table
        :data="tableData"
        size="small"
        border
        style="width: 100%"
        :summary-method="getSummaries"
        :span-method="objectSpanMethod"
      >
        <el-table-column prop="level" label="类目" />
        <el-table-column prop="level1" label="一级项目" />
        <el-table-column prop="level2" label="二级项目" />
        <template v-if="ifExpandAll">
          <el-table-column prop="label" label="项目" />
          <el-table-column prop="dscrp" label="内容" width="160" />
          <el-table-column prop="qty" label="数量" align="right" />
          <el-table-column prop="useqty" label="用量" align="right" />
          <el-table-column prop="price" label="单价" align="right" v-if="pricePower" />
        </template>
        <template v-else-if="!ifExpandAll && !pricePower">
          <el-table-column prop="qty" label="数量" align="right" />
          <el-table-column prop="useqty" label="用量" align="right" />
        </template>
        <template v-if="pricePower">
          <el-table-column prop="costamt_2" label="标准金额" align="right" :formatter="formatter" />
          <el-table-column prop="costamt_1" label="散单金额" align="right" :formatter="formatter" />
          <el-table-column prop="costamt_4" label="小单金额" align="right" :formatter="formatter" />
          <el-table-column prop="costamt_3" label="大单金额" align="right" :formatter="formatter" />
        </template>
      </el-table>

      <!-- <vxe-table
        border="full"
        ref="tableRef"
        :tree-config="treeConfig"
        :data="tableData"
        @toggle-tree-expand="toggleExpandChangeEvent"
      >
        <vxe-column field="label" title="项目" tree-node width="120"></vxe-column>
        <vxe-column field="dscrp" title="内容" width="160"></vxe-column>
        <vxe-column field="qty" title="数量"></vxe-column>
        <vxe-column field="costamt" title="数量"></vxe-column>
        <template v-if="iforigin && !ifShowOrigin">
          <vxe-column field="costamt_1" title="散单金额"></vxe-column>
          <vxe-column field="costamt_1" title="标准金额"></vxe-column>
          <vxe-column field="costamt_1" title="大单金额"></vxe-column>
          <vxe-column field="costamt_1" title="小单金额"></vxe-column>
        </template>
        <vxe-column field="useqty" title="用量"></vxe-column>
        <vxe-column field="price" title="单价"></vxe-column>
      </vxe-table> -->
    </template>

    <template v-else>
      <el-table
        :data="tableData"
        height="100%"
        size="small"
        border
        style="width: 100%"
        show-summary
        :summary-method="getSummaries"
        :span-method="objectSpanMethod"
      >
        <el-table-column prop="label" label="项目" />
        <el-table-column prop="dscrp" label="内容" width="160" />
        <el-table-column prop="qty" label="数量" align="right" />
        <el-table-column prop="costamt" label="金额" align="right" />
        <el-table-column prop="useqty" label="用量" align="right" />
        <el-table-column prop="price" label="单价" align="right" />
      </el-table>
      <!-- <el-table
        :data="tableData"
        size="small"
        border
        style="width: 100%"
        show-summary
        :summary-method="getSummaries"
        :span-method="objectSpanMethod"
      >
        <el-table-column prop="label" label="项目" />
        <el-table-column prop="dscrp" label="内容" width="160" />
        <el-table-column prop="qty" label="数量" align="right" />
        <el-table-column prop="costamt" label="金额" align="right" />
        <template v-if="iforigin && !ifShowOrigin">
          <el-table-column prop="costamt_1" label="散单金额" align="right" />
          <el-table-column prop="costamt_2" label="标准金额" align="right" />
          <el-table-column prop="costamt_3" label="大单金额" align="right" />
          <el-table-column prop="costamt_4" label="小单金额" align="right" />
        </template>
        <el-table-column prop="useqty" label="用量" align="right" />
        <el-table-column prop="price" label="单价" align="right" />
      </el-table> -->
      <!-- <el-table
        ref="elTableRef"
        :data="tableData2"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        border
        :default-expand-all="ifExpandAll"
        :span-method="objectSpanMethod3"
        :expand-change="expandChangeFunc"
      >
        <el-table-column prop="label" label="Date" />
        <el-table-column prop="name" label="Name" />
        <el-table-column prop="address" label="Address" />
      </el-table> -->
    </template>
  </LjDrawer>
</template>

<script setup lang="tsx" name="mattressQuoteLjDrawerQuoteList">
import { ref, computed, reactive, nextTick } from "vue";
import LjDrawer from "@/components/LjDrawer/index.vue";
import { useDesign } from "@/hooks/useDesign";
import { formatTime, formatAmount3, floatAdd } from "@/utils/index";
import { isFunction } from "@/utils/is";
import { cloneDeep, pick } from "lodash-es";
import { useUserStore } from "@/stores/modules/user";
import { CommonDynamicSelect } from "@/api/modules/common";
import { useHooksCpQuote } from "../hooks/cpQuote";
import { isFilterPrice, autoMergeCells } from "@/utils/index";

interface WidgetProps {
  // data: any;
  iforigin: boolean;
}

// interface WidgetTableItem {
//   label: string;
//   dscrp: any;
//   qty?: number | string;
//   costamt?: number | string;
//   useqty?: number | string;
//   price?: number | string;
//   [key: string]: any;
// }

const props = withDefaults(defineProps<WidgetProps>(), {
  iforigin: false
});

const formatter = (row: any, column: any, cellValue: any, index: any) => {
  return isFilterPrice(cellValue);
};

const { prefixCls } = useDesign("ljdrawer-quotelist");
const { userInfo } = useUserStore();
const { enumMap, tableData, oriTableData, wf_retrieve_qingdan } = useHooksCpQuote();

const pricePower = computed(() => {
  return userInfo.usermode == 0;
});

const emits = defineEmits(["export"]);

const LjDrawerRef = ref();
const elTableRef = ref();
const tableRef = ref();
const mainData = ref<any>({});
// const mainData = ref<any>({});
const ifExpandAll = ref<any>(true);

const isCurrency = computed(() => {
  return mainData.value.data?.moneyrate != 1 ? "美金" : "人民币";
});

// const tableData2: any[] = [
//   {
//     id: 1,
//     label: "2016-05-02",
//     name: "wangxiaohu",
//     address: "No. 189, Grove St, Los Angeles"
//   },
//   {
//     id: 2,
//     label: "2016-05-04",
//     name: "wangxiaohu",
//     address: "No. 189, Grove St, Los Angeles"
//   },
//   {
//     id: 3,
//     label: "2016-05-01",
//     name: "wangxiaohu",
//     address: "No. 189, Grove St, Los Angeles",
//     children: [
//       {
//         id: 31,
//         label: "2016-05-01",
//         name: "wangxiaohu",
//         address: "No. 189, Grove St, Los Angeles"
//       },
//       {
//         id: 32,
//         label: "2016-05-01",
//         name: "wangxiaohu",
//         address: "No. 189, Grove St, Los Angeles"
//       }
//     ]
//   },
//   {
//     id: 4,
//     label: "2016-05-03",
//     name: "wangxiaohu",
//     address: "No. 189, Grove St, Los Angeles"
//   }
// ];

const treeConfig = reactive<any>({
  transform: true,
  rowField: "id",
  parentField: "parentId"
});

const toggleExpandChangeEvent: any = params => {
  const $table = tableRef.value;
  if ($table) {
    const { row, expanded } = params;
    console.log("节点展开事件", expanded, "获取父节点：", $table.getParentRow(row));
  }
};

const ifShowOrigin = ref(false);
const originData = ref<any>();

const setOriginData = () => {
  let _data = cloneDeep(mainData.value);
  if (ifShowOrigin.value) {
    // 旧报价
    fields.value.map(item => {
      let _rp = originData.value.find(itm => itm.label.replace(/【/g, "").replace(/】/g, "") === item.replacelabel);
      if (_rp) {
        _data.data[item.field] = _rp.value;
      }
    });
    let _rp = originData.value.find(itm => itm.label.replace(/【/g, "").replace(/】/g, "") === "散单金额");
    if (_rp) {
      _data.data.foreign_cost = _rp.value;
    }
  }
  mainData.value = _data;
  wf_retrieve_qingdan(_data, !ifShowOrigin.value, ifExpandAll.value);
};

const handleOpenOriginQuote = () => {
  ifShowOrigin.value = !ifShowOrigin.value;

  console.log("handleOpenOriginQuote>>>>>  ", mainData.value);
  setOriginData();
};
const toggleRowExpansionAll = () => {
  wf_retrieve_qingdan(mainData.value, !ifShowOrigin.value, ifExpandAll.value);
  // data.forEach(async item => {
  //   // const elTableRef = await getElTableExpose()
  //   elTableRef.value?.toggleRowExpansion(item, isExpansion);
  //   if (item.children !== undefined && item.children !== null) {
  //     toggleRowExpansionAll(item.children, isExpansion);
  //   }
  // });
};

const objectSpanMethod3 = ({ row, column, rowIndex, columnIndex }: any) => {
  // // console.log("objectSpanMethod row,column, rowIndex,columnIndex :>> ", data);
  // if (column.property == "label") {
  //   let rowspan = 1;
  //   let currentVal = row.label;
  //   let lastVal = "";
  //   // 上一个
  //   if (rowIndex - 1 >= 0) {
  //     lastVal = tableData2[rowIndex - 1]?.label;
  //   }

  //   if (lastVal) {
  //     if (lastVal != currentVal) {
  //       // 计算合并行数
  //       let _span = 0;
  //       for (let i = rowIndex + 1; i < tableData2.length; i++) {
  //         if (tableData2[i].label == currentVal) {
  //           _span++;
  //         } else {
  //           break;
  //         }
  //       }
  //       rowspan += _span;
  //       console.log("rowspan _span :>> ", lastVal, currentVal, rowspan, _span);
  //     } else {
  //       rowspan = 0;
  //     }
  //   }

  //   return {
  //     rowspan,
  //     colspan: rowspan > 0 ? 1 : 0
  //   };
  // }

  // //定义需要合并的列字段，有哪些列需要合并，就自定义添加字段即可
  // const fields = ["label"];
  // // 当前行的数据
  // const cellValue = row[column.property];
  // // 判断只合并定义字段的列数据
  // if (cellValue && fields.includes(column.property)) {
  //   const prevRow = tableData2[rowIndex - 1]; //上一行数据
  //   let nextRow = tableData2[rowIndex + 1]; //下一行数据
  //   // 当上一行的数据等于当前行数据时，当前行单元格隐藏
  //   if (prevRow && prevRow[column.property] === cellValue) {
  //     return { rowspan: 0, colspan: 0 };
  //   } else {
  //     // 反之，则循环判断若下一行数据等于当前行数据，则当前行开始进行合并单元格
  //     let countRowspan = 1; //用于合并计数多少单元格
  //     while (nextRow && nextRow[column.property] === cellValue) {
  //       nextRow = tableData2[++countRowspan + rowIndex];
  //     }
  //     if (countRowspan > 1) {
  //       return { rowspan: countRowspan, colspan: 1 };
  //     }
  //   }
  // }

  if (columnIndex === 0) {
    if (rowIndex === 2) {
      return {
        rowspan: 3,
        colspan: 1
      };
    } else if (rowIndex >= 3 && rowIndex < 4) {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }

  console.log("elTableRef.value :>> ", elTableRef.value);
};

const expandChangeFunc = () => {};

const show = (params: any, originReplace?: any) => {
  console.log("show>>>>>  ", params, originReplace);
  originData.value = [];
  if (ifShowOrigin.value) {
    setOriginData();
  }
  mainData.value = cloneDeep(params);
  // showData.value = cloneDeep(params);
  wf_retrieve_qingdan(params, !ifShowOrigin.value, ifExpandAll.value);

  LjDrawerRef.value.show();
  // nextTick(() => {
  //   let mergeCells = autoMergeCells(tableRef.value, ["label"]);
  //   console.log("resetMergeCellsInner autoMergeCells  :>> ", mergeCells);
  //   tableRef.value.setMergeCells(mergeCells);
  // });
};

const isFilterTime = time => {
  return formatTime(time, "{y}-{m}-{d}", false);
};

const fields = computed(() => {
  if (!ifShowOrigin.value) {
    const { data, replace } = mainData.value;
    console.log("fieldsfields data :>> ", mainData.value);

    let _enum = enumMap.value.get("mattresstypeid");
    let result = "";
    if (_enum) {
      result = _enum.find(t => t.value == data.mattresstypeid).label ?? "";
    }

    let arr = [];
    if (Number(data.if_m_chai) == 1) {
      arr.push("面拆");
    }
    if (Number(data.if_z_chai) == 1) {
      arr.push("中拆");
    }
    if (Number(data.if_d_chai) == 1) {
      arr.push("底拆");
    }
    if (Number(data.if_n_butao) == 1) {
      arr.push("内布套");
    }
    if (Number(data.if_w_butao) == 1) {
      arr.push("外布套");
    }

    let _managerate = 0;
    let isFormulaValue = replace.find(o => o.label.indexOf("管理费用点") > -1);
    if (isFormulaValue) {
      _managerate = isFilterPrice(isFormulaValue.value);
    }
    let _com_profitrate = 0;
    isFormulaValue = replace.find(o => o.label.indexOf("公司利润点（部门）") > -1);
    if (isFormulaValue) {
      _com_profitrate = isFilterPrice(isFormulaValue.value);
    }
    return [
      { label: "核价编码", value: data.mattresscode },
      { label: "核价名称", value: data?.mattressname == "" ? "未命名" : data?.mattressname },
      { label: "床垫类别", value: result },
      { label: "床垫规格", value: `${data.mattress_width} * ${data.mattress_length} * ${data.mattress_height}` },
      { label: "拆装、布套", value: arr.join(" ") },
      { label: "地区", value: data.area ?? "" },
      { label: "柜型", value: data.cabinet_type ?? "" },
      { label: "管理费用点", value: _managerate ?? "", type: "variable", field: "managerate" },
      {
        label: "公司利润点（部门）",
        value: _com_profitrate ?? "",
        type: "variable",
        field: "com_profitrate",
        jointo: "公司利润点"
      },
      { label: "部门利润率", value: data.dept_profitrate ?? "", type: "variable", field: "dept_profitrate" }
    ];
  } else {
    return [
      { label: "财务底价", field: "nottax_dept_cost", replacelabel: "部门不含税价" },
      { label: "佣金点数", field: "commission", replacelabel: "佣金点数" },
      { label: "税率", field: "taxrate", replacelabel: "税率" },
      { label: "额外点数", field: "other_rate", replacelabel: "额外点数" },
      { label: "额外费用", field: "extras_cost", replacelabel: "额外费用" },
      { label: "汇率", field: "moneyrate", replacelabel: "汇率" },
      { label: "款式费用", field: "hrcost", replacelabel: "人工费用" },
      { label: "边带费用", field: "biandaicost", replacelabel: "边带费用" },
      { label: "总成本", field: "total_cost", replacelabel: "车间成本" },
      { label: "工厂利润率", field: "profitrate", replacelabel: "工厂利润率" },
      { label: "工艺点数", field: "profitrate_point", replacelabel: "工艺点数" },
      { label: "不含税出厂价", field: "nottax_factory_cost", replacelabel: "不含税出厂价" },
      { label: "部门利润率", field: "dept_profitrate", replacelabel: "部门利润率" },
      { label: "FOB费用", field: "fob", replacelabel: "FOB" },
      { label: "部门售价", field: "nottax_dept_cost", replacelabel: "部门不含税价" },
      { label: "让利点数", field: "dept_profitrate_rangli", replacelabel: "部门让利点数" },
      { label: "海绵款扣点", field: "haimian_point", replacelabel: "海绵扣点" }
    ];
  }
});

const statisticData = ref([
  {
    label: "【散单金额】",
    value: 0,
    origin: 0,
    key: "【部门含税价】",
    type: 1
  },
  {
    label: "【小单金额】",
    value: 0,
    origin: 0,
    key: "【部门含税价】",
    type: 4
  },
  {
    label: "【标准金额】",
    value: 0,
    origin: 0,
    key: "【部门含税价】",
    type: 2
  },
  {
    label: "【大单金额】",
    value: 0,
    origin: 0,
    key: "【部门含税价】",
    type: 3
  }
]);

const getStaticData = computed(() => {
  let arr = statisticData.value.filter(o => {
    // let tg = val.find(item => item.label === o.key);

    let tg = mainData.value.differ.find(item => item.type === o.type);
    if (tg) {
      let tgRl = tg.replace.find(item => item.label === o.key);
      o.label = o.label.replace("【", "").replace("】", "");
      o.value = tgRl ? tgRl.value : 0;
      console.log("tgRl,  :>> ", props.iforigin, tgRl);
      if (props.iforigin) {
        let tgori = tg.replace_origin.find(item => item.label === o.key);
        o.origin = tgori ? tgori.value : 0;
      }
    }
    // if (o?.power) {
    //   return o.power();
    // } else {
    return true;
    // }
  });

  return arr;
});

const getSummaries = (param: any) => {
  const { columns, data } = param;
  console.log("getSummaries param :>> ", param);
  const sums: any[] = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = <div>材料合计：</div>;
      return;
    }
    const values = data.map(item => Number(item[column.property]?.toString().replace(/,/g, "")));
    if (column.property == "costamt" && !values.every(value => Number.isNaN(value))) {
      // console.log("values :>> ", values);
      sums[index] = `${values.reduce((prev, curr) => {
        // console.log("prev,curr :>> ", prev, curr);
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return floatAdd(prev, curr);
        } else {
          return prev;
        }
      }, 0)}`;
    } else {
      sums[index] = "";
    }
  });

  return sums;
};

const objectSpanMethod = (data: any) => {
  const { row, column, rowIndex, columnIndex } = data;
  // console.log("objectSpanMethod row,column, rowIndex,columnIndex :>> ", data);
  let columnsName = ["level", "level1", "label"];
  ifExpandAll.value && columnsName.push("level2");
  if (columnsName.includes(column.property)) {
    let rowspan = 1;
    let currentVal = row[column.property];
    let lastVal = "";
    // 上一个
    if (rowIndex - 1 >= 0) {
      lastVal = tableData.value[rowIndex - 1][column.property];
    }

    console.log(
      "objectSpanMethod lastVal rowIndex :>> ",
      lastVal,
      currentVal,
      rowIndex,
      lastVal || rowIndex == 0,
      currentVal && (lastVal || rowIndex == 0)
    );
    if (currentVal) {
      if (lastVal != currentVal) {
        // 计算合并行数
        let _span = 0;
        for (let i = rowIndex + 1; i < tableData.value.length; i++) {
          // console.log("tableData.value[i].label :>> ", tableData.value[i][column.property], currentVal, _span);
          if (tableData.value[i][column.property] == currentVal) {
            _span++;
          } else {
            break;
          }
        }
        rowspan += _span;
      } else {
        rowspan = 0;
      }
    }
    // console.log("rowspan _span :>> ", lastVal, currentVal, rowspan);

    return {
      rowspan,
      colspan: rowspan > 0 ? 1 : 0
    };
  }
};

const handleExportExcel = () => {
  emits("export", ifExpandAll.value, ifShowOrigin.value, fields.value);
};

defineExpose({
  show
});
</script>
