<template>
  <LjDetail
    name="mattressInterfaceDetail"
    ref="LjDetailRef"
    v-bind="detailProps"
    :data="mainData"
    v-model:order-status="orderStatus"
    :action="orderDefaultAction"
    @after-mounted="funcAfterMound"
    :if-layout-editable="false"
    :search-col="{ xs: 3, sm: 3, md: 3, lg: 3, xl: 3 }"
    :basic-group-col="{ xs: 3, sm: 3, md: 3, lg: 3, xl: 3 }"
  >
    <template #mattressYW>
      <LjVxeTable
        ref="VxeTableMxRef"
        row-key="key"
        table-cls=""
        :data="mattressYWList"
        :columns="columns_yw"
        :dwname="DwnameEnum.mattressInterfaceYw"
        :request-auto="false"
        :table-props="tableProps_mx"
        :tool-button="[]"
        :auto-load-layout="false"
        collapseButtons
      >
      </LjVxeTable>
    </template>
    <template #tabNavRight v-if="orderStatus">
      <div class="flx-center flx-end flx-1">
        <LjHeaderMenu group-cls="flx-end" :action="qdAction"></LjHeaderMenu>
      </div>
    </template>
    <template #mattressQD>
      <el-row class="h-full" :gutter="10">
        <el-col :span="6" class="h-full">
          <LjVxeTable
            ref="YwTableRef"
            row-key="key"
            table-cls="h-full"
            :data="mattressYWList"
            :columns="columns_yw_qd"
            :dwname="DwnameEnum.mattressInterfaceYw"
            :request-auto="false"
            :table-props="tableProps_mx"
            :tool-button="[]"
            :auto-load-layout="false"
            collapseButtons
          >
          </LjVxeTable>
        </el-col>
        <el-col :span="18" class="h-full">
          <LjVxeTable
            ref="QdTableRef"
            row-key="key"
            table-cls="h-full"
            :data="mattressQDList"
            :columns="columns_qd"
            :dwname="DwnameEnum.mattressInterfaceQd"
            :request-auto="false"
            :table-props="tableProps_mx"
            :tool-button="[]"
            :auto-load-layout="false"
            collapseButtons
          >
          </LjVxeTable>
        </el-col>
      </el-row>
    </template>
  </LjDetail>

  <MattressDialog ref="MattressDialogRef" v-bind="MattressDialogProps" />
  <MtrldefErpDialog ref="MtrldefErpDialogRef" v-bind="MtrldefErpDialogProps" />
</template>

<script setup lang="tsx" name="mattressInterfaceDetail">
import { ref, watch, reactive, inject, onMounted, computed, nextTick } from "vue";
import { DwnameEnum } from "@/enums/dwnameEnum";
import LjDetail from "@/components/LjDetail/index.vue";
import { DetailProp } from "@/components/LjDetail/interface";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import { useHooks } from "./hooks/index";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { CommonDynamicSelect, GetERPWrkGrpList, GetERPWrkGrpList2 } from "@/api/modules/common";
import { SaveMattressInterface } from "@/api/modules/quote";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import mittBus from "@/utils/mittBus";
import { MittEnum } from "@/enums/mittEnum";
import MattressDialog from "@/views/system/selector/mattress/index.vue";
import MtrldefErpDialog from "@/views/system/selector/mtrldefErp/index.vue";
import { formatToDate } from "@/utils/dateUtil";

interface detailProp {
  /**
   * @argument any 页面数据
   */
  data?: any;
  /**
   * @argument string 请求数据的api ==> 非必传
   */
  requestApi?: (params: any) => Promise<any>;
  /**
   * @argument any 基础信息，表格展示数据
   */
  // columns?: any;
  /**
   * @description 是否可编辑
   */
  status: "edit" | "new" | string;
  enum?: any;
}

const props = withDefaults(defineProps<detailProp>(), {});
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const {
  VxeTableMxRef,
  YwTableRef,
  QdTableRef,
  orderStatus,
  LjDetailRef,
  columns_detail,
  columns_yw,
  columns_yw_qd,
  columns_qd,
  mainData,
  editType,
  mattressYWList,
  mattressQDList,
  MattressDialogRef,
  MattressDialogProps,
  MtrldefErpDialogRef,
  MtrldefErpDialogProps,
  tableProps_mx,
  workgrpEnum,
  workgrpEnum2,
  configureTypeEnum,
  RetriveMattressInterface,
  RefreshMattressInterfaceList,
  RefreshMattressInterfaceQdList,
  fModelChoseMattress,
  toExcel,
  toCreateMtrl,
  toCreateORDelMtrlPf,
  toUpdateL1Planprice,
  YWAudit,
  JSAudit,
  JS2Audit,
  resetMergeCellsQd
} = useHooks(t);
const { CheckPower, CheckOption, buttonNew, buttonDefault } = useAuthButtons(t);

const initParams = ref({ mattressid: 0 as Number });

const detailProps = reactive<DetailProp>({
  dwname: DwnameEnum.mattressInterfaceDetail,
  columns: columns_detail,
  basicDefault: {},
  header: {
    foldright: {
      width: 80
    },
    fieldNames: {
      code: "sptcode",
      codeLabel: t("table.u_spt.sptcode") + "：",
      name: "name"
    }
  },
  mould: [
    {
      id: "mattressYW",
      type: "table",
      label: "产品配置"
    },
    {
      id: "mattressQD",
      type: "table",
      label: "产品清单"
    }
  ]
});

const tabRemove: Function = inject("tabRemove") as Function;
const loadingStatus = reactive({
  save: false
});

const qdAction = [
  buttonDefault({
    label: "批量设置",
    clickFunc: () => {
      let _cur = QdTableRef.value.currentEditCell;
      console.log("qdAction _cur :>> ", _cur);
      console.log("qdAction ![d) :>> ", !["wrkgrpid", "wrkgrpid2", "useqty"].includes(_cur.field));

      if (!["wrkgrpid", "wrkgrpid2", "useqty"].includes(_cur.field)) {
        return ElMessage.warning("此列暂不支持批量设置(仅支持实际用量、工组)");
      }
      // return mattressQDList.value.length == 0;
      // nextTick(() => {
      const $table = QdTableRef.value.element;

      const { visibleData } = $table.getTableData();

      console.log("qdAction _cur :>> ", _cur);

      if (visibleData) {
        let _val = visibleData[_cur.rowIndex][_cur.field];
        visibleData.map((o, idx) => {
          if (o.useqty > 0 && idx > _cur.rowIndex) {
            o[_cur.field] = _val;
          }
        });

        $table.reloadData(visibleData);
        resetMergeCellsQd();
      }
    }
  })
];

const orderDefaultAction = [
  buttonDefault({
    label: t("common.cancelText"),
    icon: "iconchevron-left",
    limited: () => {
      return !orderStatus.value;
    },
    clickFunc: item => {
      router.replace(
        `/erpapi/mattressInterface/detail?id=${LjDetailRef.value?._mainData.mattressid}&code=${LjDetailRef.value?._mainData.mattresscode}`
      );
    }
  }),
  buttonDefault({
    label: t("common.saveText"),
    loading: () => loadingStatus.save,
    limited: () => !orderStatus.value,
    clickFunc: async item => {
      try {
        await LjDetailRef.value.toValidateForm();

        ElMessageBox.confirm("是否确定要保存吗?", "询问", {
          confirmButtonText: "是",
          cancelButtonText: "否",
          type: "warning"
        }).then(async () => {
          loadingStatus.save = true;
          try {
            const res = await SaveMattressInterface({
              mattress: LjDetailRef.value?._mainData,
              interfaceList: mattressYWList.value,
              qdList: mattressQDList.value
            })
              .then(res => {
                ElNotification({
                  title: "温馨提示",
                  message: t("sys.api.sueccessToSave"),
                  type: "success"
                });
                tabRemove(route.fullPath);
                router.push(
                  `/erpapi/mattressInterface/detail?id=${LjDetailRef.value?._mainData.mattressid}&code=${LjDetailRef.value?._mainData.mattresscode}`
                );
                loadingStatus.save = false;
              })
              .catch(error => {
                console.log("error !! :>> ", error);
                loadingStatus.save = false;
              });
          } catch (error) {
            loadingStatus.save = false;
            ElMessage.error(t("sys.api.operationFailed"));
          }
        });
      } catch (error) {
        for (const key in error) {
          if (Object.prototype.hasOwnProperty.call(error, key)) {
            const element = error[key];
            ElMessage.error(element[0].message);
          }
        }
        return false;
      }
    }
  }),
  [
    buttonDefault({
      label: "刷新带出配置",
      limited: () => {
        return !orderStatus.value || editType.value == 3;
      },
      clickFunc: item => {
        RefreshMattressInterfaceList(LjDetailRef.value?._mainData.mattressid, 1);
      }
    }),
    buttonDefault({
      label: "复制配置",
      limited: () => {
        return !orderStatus.value || editType.value == 3;
      },
      clickFunc: item => {
        fModelChoseMattress().then((res: any) => {
          RefreshMattressInterfaceList(res.mattressid, 1);
        });
      }
    }),
    buttonDefault({
      label: "重新生成配置项目",
      limited: () => {
        return !orderStatus.value || editType.value != 1;
      },
      clickFunc: item => {
        RefreshMattressInterfaceList(LjDetailRef.value?._mainData.mattressid, 0);
      }
    })
  ],
  [
    buttonDefault({
      label: "刷新清单",
      limited: () => {
        return !orderStatus.value;
      },
      clickFunc: item => {
        RefreshMattressInterfaceQdList(LjDetailRef.value?._mainData.mattressid, 1);
      }
    }),
    buttonDefault({
      label: "复制清单",
      limited: () => {
        return !orderStatus.value;
      },
      clickFunc: item => {
        fModelChoseMattress().then((res: any) => {
          RefreshMattressInterfaceQdList(res.mattressid, 1, 0);
        });
      }
    }),
    buttonDefault({
      label: "重新生成清单",
      limited: () => {
        return !orderStatus.value;
      },
      clickFunc: item => {
        RefreshMattressInterfaceQdList(LjDetailRef.value?._mainData.mattressid, 0);
      }
    })
  ],
  [
    buttonDefault({
      label: "业务补充",
      power: 79,
      limited: () => {
        return !!orderStatus.value || LjDetailRef.value?._mainData.xd_flag == 1;
      },
      clickFunc: item => {
        routeToEdit(1);
      }
    }),
    buttonDefault({
      label: "业务审核",
      power: 80,
      limited: () => {
        return !!orderStatus.value;
      },
      clickFunc: item => {
        const curRecords = [LjDetailRef.value?._mainData];

        YWAudit(1, curRecords, () => {
          LjDetailRef.value.refresh();
        });
      }
    }),
    buttonDefault({
      label: "业务撤审",
      power: 81,
      limited: () => {
        return !!orderStatus.value;
      },
      clickFunc: item => {
        const curRecords = [LjDetailRef.value?._mainData];

        YWAudit(0, curRecords, () => {
          LjDetailRef.value.refresh();
        });
      }
    })
  ],
  [
    buttonDefault({
      label: "产品补充",
      power: 82,
      limited: () => {
        return !!orderStatus.value;
      },
      clickFunc: item => {
        routeToEdit(2);
      }
    }),
    buttonDefault({
      label: "产品补充审核",
      power: 83,
      limited: () => {
        return !!orderStatus.value;
      },
      clickFunc: item => {
        const curRecords = [LjDetailRef.value?._mainData];

        JSAudit(1, curRecords, () => {
          LjDetailRef.value.refresh();
        });
      }
    }),
    buttonDefault({
      label: "产品补充撤审",
      power: 84,
      limited: () => {
        return !!orderStatus.value;
      },
      clickFunc: item => {
        const curRecords = [LjDetailRef.value?._mainData];

        JSAudit(0, curRecords, () => {
          LjDetailRef.value.refresh();
        });
      }
    })
  ],
  [
    buttonDefault({
      label: "清单补充",
      power: 85,
      limited: () => {
        return !!orderStatus.value;
      },
      clickFunc: item => {
        routeToEdit(3);
      }
    }),
    buttonDefault({
      label: "清单补充审核",
      power: 86,
      limited: () => {
        return !!orderStatus.value;
      },
      clickFunc: item => {
        const curRecords = [LjDetailRef.value?._mainData];

        JS2Audit(1, curRecords, () => {
          LjDetailRef.value.refresh();
        });
      }
    }),
    buttonDefault({
      label: "清单补充撤审",
      power: 87,
      limited: () => {
        return !!orderStatus.value;
      },
      clickFunc: item => {
        const curRecords = [LjDetailRef.value?._mainData];

        JS2Audit(0, curRecords, () => {
          LjDetailRef.value.refresh();
        });
      }
    })
  ],
  buttonDefault({
    label: "生成/更新物料",
    power: 90,
    limited: () => {
      return !!orderStatus.value;
    },
    clickFunc: item => {
      toCreateMtrl(1, LjDetailRef.value?._mainData.mattressid);
    }
  }),
  [
    buttonDefault({
      label: "生成金蝶清单",
      power: 90,
      limited: () => {
        return !!orderStatus.value;
      },
      clickFunc: item => {
        toCreateORDelMtrlPf(1, LjDetailRef.value?._mainData.mattressid);
      }
    })
    // buttonDefault({
    //   label: "删除金蝶清单",
    //   power: 91,
    //   clickFunc: item => {
    //     toCreateORDelMtrlPf(0, LjDetailRef.value?._mainData.mattressid);
    //   }
    // })
    // buttonDefault({
    //   label: "更新计划价",
    //   power: 91,
    //   limited: () => {
    //     return !!orderStatus.value;
    //   },
    //   clickFunc: item => {
    //     toUpdateL1Planprice(LjDetailRef.value?._mainData.mattressid);
    //   }
    // })
  ],
  buttonDefault({
    label: t("common.back"),
    clickFunc: item => {
      router.push(`/erpapi/mattressInterface`);
    }
  })
];

const routeToEdit = (type: any) => {
  console.log("routeToEdit mainData :>> ", mainData);
  const _cur = mainData.value[0];
  router.push(`/erpapi/mattressInterface/${type}/edit?id=${_cur.mattressid}&code=${_cur.mattresscode}&type=${type}`);
};

/**
 * @description 页面数据加载完成
 */
const funcAfterMound = async () => {
  console.log("onMounted detail sale start!!!! :>> ");
  if (!orderStatus.value) {
    // 详情页
    // gotoSummy(8000);
  } else {
    // 新增/编辑
    tableProps_mx.value.editConfig.enabled = true;
    // tableProps_mx_yw.value.editConfig.enabled = true;
    // tableProps_mx_qd.value.editConfig.enabled = true;
  }

  console.log("onMounted detail sale start LjDetailRef.value.mainData :>> ", LjDetailRef.value);

  if (orderStatus.value != "new") {
  }
};

onMounted(async () => {
  console.log("route onMounted:>> ", route);
  console.log("route onMounted:>> ", route.params);
  console.log("route onMounted:>> ", route.params.id);

  const result = await GetERPWrkGrpList();

  if (result.workgroupList) {
    workgrpEnum.value = result.workgroupList.map(item => {
      return {
        label: item.wrkgrpname,
        value: item.wrkgrpid,
        code: item.wrkgrpcode
      };
    });

    // columns_qd.value = columns_qd.value.map(item => {
    //   if (item.field == "wrkgrpid") {
    //     item.editRender.options = workgrpEnum.value;
    //   }
    //   return item;
    // });
  }

  const result2 = await GetERPWrkGrpList2();
  workgrpEnum2.value = result2.datatable ?? [];

  if (route.query?.id) {
    // 刷新数据
    initParams.value.mattressid = Number(route.query?.id);
    editType.value = Number(route.query?.type);
    console.log("detail onMounted initParams.value :>> ", initParams.value);
    console.log("领用工组领用工组领用工组领用工组 columns_qd.value :>> ", columns_qd.value);
    await RetriveMattressInterface(initParams.value.mattressid.valueOf());
  }
});
</script>
