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

    <el-descriptions :column="3">
      <template #title>
        <span class="text-body-b">报价日期：</span>
        <span class="text-body-b" v-if="data.createtime">{{ isFilterTime(data.createtime) }}</span>
      </template>
      <template #extra>
        <span class="text-body-b">报价金额：</span>
        <span class="text-body-b">{{ isFilterPrice(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(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" />
      <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";

interface WidgetProps {
  data: any;
  mxdata?: any;
  /**
   * @description 属性枚举
   */
  enumMap?: any;
  /**
   * @description 面料tab分类
   */
  fabricMx?: any;
  formulakindenum?: any;
}

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>(), {});

const { prefixCls } = useDesign("ljdrawer-quotelist");
const { userInfo } = useUserStore();

const LjDrawerRef = ref();

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

const show = async () => {
  await wf_retrieve_qingdan();
  LjDrawerRef.value.show();
};

const isFilterPrice = data => {
  return formatAmount3({ val: data });
};

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

const tableData = ref<WidgetTableItem[]>([]);

const fields = [
  { label: "财务底价", field: "nottax_dept_cost" },
  { label: "佣金点数", field: "commission" },
  { label: "税率", field: "taxrate" },
  { label: "额外点数", field: "other_rate" },
  { label: "额外费用", field: "extras_cost" },
  { label: "汇率", field: "moneyrate" },
  { label: "款式费用", field: "hrcost1" },
  { label: "边带费用", field: "biandaicost1" },
  { label: "总成本", field: "total_cost_1" },
  { label: "工厂利润率", field: "profitrate" },
  { label: "工艺点数", field: "profitrate_point" },
  { label: "不含税出厂价", field: "nottax_factory_cost_1" },
  { label: "部门利润率", field: "dept_profitrate" },
  { label: "FOB费用", field: "fob" },
  { label: "部门售价", field: "nottax_dept_cost_1" },
  { label: "让利点数", field: "dept_profitrate_rangli" },
  { label: "海绵款扣点", field: "haimian_point" }
];

const oriTableData = ref<WidgetTableItem[]>([
  {
    label: "核价编码",
    dscrp: () => props.data.mattresscode
  },
  {
    label: "核价名称",
    dscrp: () => props.data.mattressname
  },
  {
    label: "床垫类别",
    dscrp: () => {
      let _enum = props.enumMap.get("mattresstypeid");
      let result = "";
      if (_enum) {
        result = _enum.find(t => t.value == props.data.mattresstypeid).label ?? "";
      }
      return result;
    }
  },
  {
    label: "床垫规格",
    dscrp: () => {
      return `${props.data.mattress_width} * ${props.data.mattress_length} * ${props.data.mattress_height}`;
    }
  },
  {
    label: "拆装、布套",
    dscrp: () => {
      let arr = [];
      if (Number(props.data.if_m_chai) == 1) {
        arr.push("面拆");
      }
      if (Number(props.data.if_z_chai) == 1) {
        arr.push("中拆");
      }
      if (Number(props.data.if_d_chai) == 1) {
        arr.push("底拆");
      }
      if (Number(props.data.if_n_butao) == 1) {
        arr.push("内布套");
      }
      if (Number(props.data.if_w_butao) == 1) {
        arr.push("外布套");
      }
      return arr.join(" ");
    }
  }
]);

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 f_get_bednet_qingdan = (data: any) => {
//   let _params = {
//       dsname: "web_his_price",
//       queryparams: {
//         arg_id: 0,
//         arg_typeid: 1
//       }
//     };
//     let res = await CommonDynamicSelect(_params);
//     let _data = [];
//     if (res?.datatable?.length) {
//       _data=res?.datatable
//     }
// };

/**
 * @description 刷新报价清单
 */
const wf_retrieve_qingdan = () => {
  tableData.value = [];
  let _tData = cloneDeep(oriTableData.value);
  tableData.value = _tData.map(item => {
    for (const key in item) {
      if (isFunction(item[key])) {
        item[key] = item[key]();
      }
    }
    return item;
  });

  console.log("props.mxdata data:>> ", props.mxdata, props.data);
  let _mxitm = null;
  props.mxdata.map(item => {
    switch (item.field) {
      case "tabpage_8":
      case "tabpage_9":
      case "tabpage_10":
      case "tabpage_11":
      case "tabpage_12":
        _mxitm = props.fabricMx.find(t => t.name == item.field);
        item.data.map(itm => {
          if ((Number(itm.mtrlid ?? 0) > 0 || Number(itm.costamt ?? 0) != 0) && _mxitm.type.includes(Number(itm.formulakind))) {
            let result: any = {};
            result.label = itm.chastr != "" ? itm.chastr : item.label;
            let _formulaName = "";
            if (props.formulakindenum) {
              _formulaName = props.formulakindenum.find(t => t.value == itm.formulakind)?.label ?? "";
            }

            _formulaName = _formulaName.replace(item.replace, "");

            console.log("_formulaName  rp:>> ", _formulaName, item.replace);
            result.dscrp = `${_formulaName}：${itm.mtrlname}`;

            if (Number(itm.thickness) > 0) {
              result.dscrp += ` 厚度：${isFilterPrice(itm.thickness)}`;
            }
            result.qty = Number(itm.qty);
            if (userInfo.usermode == 0) {
              result.costamt = isFilterPrice(itm.costamt ?? 0);
              result.useqty = Number(itm.useqty ?? 0);
              result.price = isFilterPrice(itm.price ?? 0);
            }
            tableData.value.push(result);
          }
        });
        break;
      case "tabpage_13":
        _mxitm = props.fabricMx.find(t => t.name == item.field);
        item.data.map(itm => {
          if ((Number(itm.mtrlid ?? 0) > 0 || Number(itm.costamt ?? 0) != 0) && !_mxitm.type.includes(Number(itm.formulakind))) {
            let result: any = {};
            result.label = itm.label;
            let _formulaName = "";
            if (props.formulakindenum) {
              _formulaName = props.formulakindenum.find(t => t.value == itm.formulakind)?.label ?? "";
            }

            _formulaName = _formulaName.replace(item.replace, "");
            result.dscrp = `${_formulaName}：${itm.mtrlname}`;

            if (Number(itm.thickness) > 0) {
              result.dscrp += ` 厚度：${isFilterPrice(itm.thickness)}`;
            }
            result.qty = Number(itm.qty);
            if (userInfo.usermode == 0) {
              result.costamt = isFilterPrice(itm.costamt ?? 0);
              result.useqty = Number(itm.useqty ?? 0);
              result.price = isFilterPrice(itm.price ?? 0);
            }
            tableData.value.push(result);
          }
        });
        break;
      case "cushions": // 垫层
        item.data.cushions.map(itm => {
          if (Number(itm.mtrlid ?? 0) > 0 || Number(itm.costamt ?? 0) != 0 || [999].includes(Number(itm.formulakind))) {
            let result: any = {};
            let _formulaName = "";
            if (props.formulakindenum) {
              _formulaName = props.formulakindenum.find(t => t.value == itm.formulakind)?.label ?? "";
            }

            result.label = _formulaName;
            result.dscrp = itm.mtrlname;

            if (![999].includes(Number(itm.formulakind))) {
              if (Number(itm.thickness) > 0) {
                result.dscrp += ` 厚度：${isFilterPrice(itm.thickness)}`;
              }
              result.qty = Number(itm.qty);
              if (userInfo.usermode == 0) {
                result.costamt = isFilterPrice(itm.costamt ?? 0);
                result.useqty = Number(itm.useqty ?? 0);
                result.price = isFilterPrice(itm.price ?? 0);
              }
            } else {
              // 999是床网
              // long ll_bednetid = 0
              // decimal ld_bednet_height = 0
              // s_bednet_qd s_bednet_qingdan[]
              // string arg_temp_msg
              // ll_bednetid = 0
              // if dw_chuangwang.rowcount() = 1 then //单床网
              //   ll_bednetid = dw_chuangwang.object.mtrlid[1]
              //   f_get_bednet_qingdan(ll_bednetid,s_bednet_qingdan,arg_temp_msg)
              //   if upperbound(s_bednet_qingdan) > 0 then
              //     dw_qingdan.Object.str1[ll_row] = s_bednet_qingdan[1].pznamemx
              //     dw_qingdan.Object.str2[ll_row] = '1'
              //     IF sys_usermode = 0 THEN //管理员模式
              //       dw_qingdan.Object.str3[ll_row] = string( s_bednet_qingdan[1].amt,'#,##0.00')
              //     end if
              //   end if
              // else //多床网
              //   for k = 1 to dw_chuangwang.rowcount()
              //     ll_bednetid = 0
              //     ld_bednet_height = 0
              //     ll_bednetid = dw_chuangwang.object.mtrlid[k]
              //     SELECT u_bednetmx.bednet_height Into :ld_bednet_height From u_bednetmx Where bednetid = :ll_bednetid;
              //     if isnull(ld_bednet_height) then ld_bednet_height = 0
              //     if ld_bednet_height = dw_dianceng.object.thickness[i] then
              //       ll_bednetid = dw_chuangwang.object.mtrlid[k]
              //       f_get_bednet_qingdan(ll_bednetid,s_bednet_qingdan,arg_temp_msg)
              //       if upperbound(s_bednet_qingdan) > 0 then
              //         dw_qingdan.Object.str1[ll_row] = s_bednet_qingdan[1].pznamemx
              //         dw_qingdan.Object.str2[ll_row] = '1'
              //         IF sys_usermode = 0 THEN //管理员模式
              //           dw_qingdan.Object.str3[ll_row] = string( s_bednet_qingdan[1].amt,'#,##0.00')
              //         end if
              //       end if
              //     end if
              //   next
              // end if
            }

            tableData.value.push(result);
          }
        });
        break;
      case "accessories": // 辅料
        item.data.map(itm => {
          if (Number(itm.mtrlid ?? 0) > 0 || Number(itm.costamt ?? 0) != 0) {
            let result: any = {};
            result.label = itm.label;
            let _formulaName = "";
            if (props.formulakindenum) {
              _formulaName = props.formulakindenum.find(t => t.value == itm.formulakind)?.label ?? "";
            }

            result.label = _formulaName;
            result.dscrp = itm.mtrlname;

            if (Number(itm.thickness) > 0) {
              result.dscrp += ` 厚度：${isFilterPrice(itm.thickness)}`;
            }
            result.qty = Number(itm.qty);
            if (userInfo.usermode == 0) {
              result.costamt = isFilterPrice(itm.costamt ?? 0);
              result.useqty = Number(itm.useqty ?? 0);
              result.price = isFilterPrice(itm.price ?? 0);
            }
            tableData.value.push(result);
          }
        });
        break;
      case "packag":
        console.log("packag item.data :>> ", item.data, props.formulakindenum);
        item.data.map(itm => {
          console.log("(Number(itm.mtrlid) > 0 |:>> ", Number(itm.mtrlid) > 0);
          console.log(
            "(N Number(itm.costamt) != 0) :>> ",
            Number(itm.costamt) != 0,
            Number(itm.costamt),
            itm.costamt,
            Number(itm?.costamt),
            Number(itm?.costamt) != 0
          );
          console.log(
            "(Number(itm.mtrlid) > 0 || Number(itm.costamt) != 0) :>> ",
            Number(itm.mtrlid) > 0 || Number(itm.costamt) != 0
          );
          if (Number(itm.mtrlid ?? 0) > 0 || Number(itm.costamt ?? 0) != 0) {
            let result: any = {};
            result.label = itm.label;
            let _formulaName = "";
            if (props.formulakindenum) {
              _formulaName = props.formulakindenum.find(t => t.value == itm.formulakind)?.label ?? "";
            }
            result.label = _formulaName;

            result.dscrp = Number(itm.mtrlid) > 0 ? itm.mtrlname : _formulaName;

            if (Number(itm.thickness) > 0) {
              result.dscrp += ` 厚度：${isFilterPrice(itm.thickness)}`;
            }
            result.qty = Number(itm.qty);
            if (userInfo.usermode == 0) {
              result.costamt = isFilterPrice(itm.costamt ?? 0);
              result.useqty = Number(itm.useqty ?? 0);
              result.price = isFilterPrice(itm.price ?? 0);
            }
            tableData.value.push(result);
          }
        });
        break;
    }
  });

  console.log("wf_retrieve_qingdan tableData.value :>> ", tableData.value);

  tableData.value.push({
    label: "地区",
    dscrp: props.data.area ?? ""
  });
  tableData.value.push({
    label: "柜型",
    dscrp: props.data.cabinet_type ?? ""
  });
};

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 :>> ", column.property, rowspan, _span);
      } else {
        rowspan = 0;
      }
    }

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

defineExpose({
  show
});
</script>
