<template>
  <LjDrawer ref="LjDrawerRef" size="50%" :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>
      </div>
    </template>

    <el-descriptions :column="3">
      <template #title>
        <span class="text-body-b">报价日期：</span>
        <span class="text-body-b" v-if="showData.data.createtime">{{ isFilterTime(showData.data.createtime) }}</span>
      </template>
      <template #extra>
        <span class="text-body-b">报价金额：</span>
        <span class="text-body-b">{{ isFilterPrice(showData.data.foreign_cost) + isCurrency }}</span>
      </template>
      <el-descriptions-item v-for="item in fields" :key="item.field" width="80">
        <template #label>
          <span class="text-secondary-text"> {{ item.label }}: </span>
        </template>
        <span class="text-body-m">{{ isFilterPrice(showData.data[item.field]) }}</span>
      </el-descriptions-item>
    </el-descriptions>

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

<script setup lang="tsx" name="mattressQuoteLjDrawerQuoteList">
import { ref, computed } 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 } 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 { prefixCls } = useDesign("ljdrawer-quotelist");
// const { userInfo } = useUserStore();
const { tableData, oriTableData, wf_retrieve_qingdan } = useHooksCpQuote();

const LjDrawerRef = ref();
const mainData = ref<any>({});
const showData = ref<any>({});

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

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

const setOriginData = () => {
  let _data = cloneDeep(mainData.value);
  if (ifShowOrigin.value) {
    // 旧报价
    fields.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;
    }
  }
  showData.value = _data;
  wf_retrieve_qingdan(_data);
};

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

  console.log("handleOpenOriginQuote>>>>>  ", mainData.value);
  setOriginData();
};

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);
  LjDrawerRef.value.show();
};

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

const fields = [
  { 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 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);
  if (column.property == "label") {
    let rowspan = 1;
    let currentVal = row.label;
    let lastVal = "";
    // 上一个
    if (rowIndex - 1 >= 0) {
      lastVal = tableData.value[rowIndex - 1]?.label;
    }

    if (lastVal) {
      if (lastVal != currentVal) {
        // 计算合并行数
        let _span = 0;
        for (let i = rowIndex + 1; i < tableData.value.length; i++) {
          if (tableData.value[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
    };
  }
};

defineExpose({
  show
});
</script>
