<template>
  <div class="table-box">
    <LjVxeTable
      ref="vxeTableRef"
      row-key="mattressid"
      :columns="columns"
      :init-param="initParams"
      :request-api="getData"
      :data-callback="dataCallback"
      :dwname="DwnameEnum.mattressQuote"
      :table-props="tableProps"
      :table-events="tableEvents"
      :auto-load-layout="false"
      :search-btn-size-extent="[]"
      pagination
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <LjHeaderMenu :update="dialogVisible" :action="action" />
      </template>
    </LjVxeTable>
  </div>
  <el-dialog v-model="dialogFormVisible" title="部门选择" width="500" draggable append-to-body>
    <el-form :model="formParam" label-width="80px">
      <el-form-item label="部门">
        <el-select v-model="formParam.deptid" placeholder="请选择部门">
          <el-option v-for="(col, index) in deptEnum" :key="index" :label="col.label" :value="col.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="地区">
        <el-select v-model="formParam.area">
          <el-option label="维持原状" value="维持原状" />
          <el-option label="普通地区" value="普通地区" />
          <el-option label="特定地区" value="特定地区" />
        </el-select>
      </el-form-item>
      <el-form-item label="柜型">
        <el-select v-model="formParam.cabinet_type">
          <el-option label="维持原状" value="维持原状" />
          <el-option label="大柜" value="大柜" />
          <el-option label="小柜" value="小柜" />
        </el-select>
      </el-form-item>
      <el-form-item label="压包数量" v-if="formParam.packtype == 0">
        <el-input-number v-model="formParam.packqty" :min="0" :max="1000" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="BatchCopyMattressAudited">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="mattressQuote">
import { ref, onMounted, inject } from "vue";
import { useRouter } from "vue-router";
import {
  SaveMattressAuditing,
  DelMattress,
  CopyMattressAudited,
  ReCalculateNoAudit,
  ReCalculateERPCost
} from "@/api/modules/quote";
import { CommonDynamicSelect } from "@/api/modules/common";
import { ColumnProps } from "@/components/LjVxeTable/interface";
import LjDrawer from "@/components/LjDrawer/index.vue";
// import PriceListDetail from "./detail.vue";
import { useHooks } from "./hooks/index";
import { useHooksCpQuote } from "./hooks/cpQuote";
import LjDialog from "@/components/LjDialog/index.vue";
import LjHeaderMenu from "@/components/LjHeaderMenu/index.vue";
import { useI18n } from "vue-i18n";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { DwnameEnum } from "@/enums/dwnameEnum";
import { formatToDateTime, formatToDate } from "@/utils/dateUtil";
import { cloneDeep } from "lodash-es";
import { useGlobalStore } from "@/stores/modules/global";
import { ElMessage, ElMessageBox } from "element-plus";
import { detailAction } from "@/components/LjDetail/interface";
import mittBus from "@/utils/mittBus";
import { MittEnum } from "@/enums/mittEnum";
import { getCurrentRecords } from "@/utils/index";
import { useUserStore } from "@/stores/modules/user";

const { t } = useI18n();
const router = useRouter();
const globalStore = useGlobalStore();
const { vxeTableRef, columns, initParams, dataCallback, gotoErpapi } = useHooks();
const { toExcelQuote } = useHooksCpQuote();
const { CheckPower, CheckOption, buttonNew, buttonDefault } = useAuthButtons(t);

// const initParams = ref({});
const dialogVisible = ref(false);
// const vxeTableRef = ref();
const dialogFormVisible = ref(false);
const deptEnum = ref([]);

const formParam = ref({
  deptid: 0,
  area: "维持原状",
  cabinet_type: "维持原状",
  packtype: 0,
  packqty: 0
});

const getData = (params: any) => {
  console.log("getData mattress params :>> ", params);
  let newParams: any = {};
  params.pageNum && (newParams.pageindex = params.pageNum);
  params.pageSize && (newParams.pagesize = params.pageSize);
  params.orderstr && (newParams.orderstr = params.orderstr);
  delete params.arg_mattressid;
  delete params.pageNum;
  delete params.pageSize;
  delete params.orderstr;
  let _params = cloneDeep(params);
  switch (_params.status_flag) {
    case "1": // 待下单
      _params.arg_xd_flag = 0;
      break;
    case "2": // 已下单
      _params.arg_xd_flag = 1;
      break;
    case "3": // 待财务审核
      _params.arg_cp_flag = 1;
      _params.arg_flag = 0;
      break;
    case "4": // 已财务审核
      _params.arg_flag = 1;
      break;
    default:
      break;
  }
  newParams.queryParams = _params;
  newParams.dsname = "web_mattress";

  return CommonDynamicSelect(newParams, DwnameEnum.mattressQuote);
  // return [];
};

const handleDBlClickTable = ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }: any) => {
  if (globalStore.detailBlank) {
    // 打开新的窗口
    const routeUrl = router.resolve({
      path: `/mattressQuote/detail`,
      query: {
        id: row.mattressid,
        code: row.mattresscode
      }
    });
    window.open(routeUrl.href, "_blank");
  } else {
    // if (currentLayout.value.right.hidden && globalStore.mxFloat?.includes("custCrmDetail")) {
    //   // 弹窗
    //   mainData.value = row;
    //   LjDrawerRef.value.show();
    // } else {
    // 打开新的标签页
    router.push(`/mattressQuote/detail?id=${row.mattressid}&code=${row.mattresscode}`);
    // }
  }
};

const rowClsNameFunc = (data: any) => {
  const { row, rowIndex, $rowIndex } = data;
  if (Number(row.flag) == 0) {
    if (Number(row.xd_flag) == 0) {
      return "vxecol-danger";
    }
    if (Number(row.xd_flag) == 1) {
      return "vxecol-blue";
    }
  }
  return "";
};
const tableProps = {
  height: "auto",
  editConfig: { trigger: "click", mode: "cell" },
  rowClassName: rowClsNameFunc,
  exportConfig: {
    filename: t("menu.rpMsttake") + formatToDate(new Date(), "YYYY-MM-DD HH:mm:ss")
  },
  treeConfig: {
    expandAll: true,
    transform: true,
    rowField: "mattressid",
    parentField: "parentid"
  },
  checkboxConfig: {
    checkStrictly: true
  }
};

// 返回绑定的事件
const tableEvents = {
  // "checkbox-change": handleCheckboxChange,
  // "checkbox-all": handleCheckboxChange,
  // "checkbox-range-change": handleCheckboxChange,
  // "current-change": handleCurrentChanged
  "cell-dblclick": handleDBlClickTable
  // "cell-click": handleClickTable
};

onMounted(() => {
  dialogVisible.value = true;
});

/**
 * @description 业务下单或财务审核操作
 * @param params 对象，入参
 */
const toAuditing = (params: any, message: string) => {
  const { curRecords } = getCurrentRecords(vxeTableRef.value);

  console.log("curRecords :>> ", curRecords);
  if (!curRecords.length) {
    ElMessage.warning(t("business.tips.mattress.records"));
    return;
  }

  let _mattressids = curRecords.map((item: any) => Number(item.mattressid));

  ElMessageBox.confirm(`是否确定要对${curRecords.length}张床垫报价单进行操作`, "询问", {
    confirmButtonText: message,
    cancelButtonText: "否",
    type: "warning"
  })
    .then(() => {
      let _params = {
        ...params,
        mattressids: _mattressids
      };
      SaveMattressAuditing(_params).then(() => {
        ElMessage.success(t("sys.api.operationSuccess"));

        vxeTableRef.value.refresh();
      });
    })
    .catch((e: TypeError) => {
      ElMessage({
        type: "info",
        message: "操作取消"
      });
    });
};

/**
 * @description 按钮展示
 */
const action: detailAction[] = [
  buttonDefault({
    label: t("common.redo"),
    clickFunc: item => {
      vxeTableRef.value.refresh();
    }
  }),
  buttonDefault({
    label: t("common.add"),
    power: 72,
    clickFunc: item => {
      console.log("inewss   nitParams.value :>> ", vxeTableRef.value.searchParam);
      let _deptid = 0;
      if (Object.keys(vxeTableRef.value.searchParam).includes("arg_deptid")) {
        _deptid = vxeTableRef.value.searchParam.arg_deptid ?? 0;
      }
      if (_deptid == 0) {
        let enumMap = vxeTableRef.value.enumMap;
        let enumdata = enumMap.get("deptid");
        if (enumdata && enumdata.length > 0) {
          _deptid = enumdata[0].value;
        }
      }
      router.push(`/mattressQuote/new?id=0&deptid=${_deptid}`);
    }
  }),
  buttonDefault({
    label: t("common.editText"),
    power: 72,
    clickFunc: item => {
      const { $table, curRecords } = getCurrentRecords(vxeTableRef.value);

      if (!curRecords.length) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
      }
      const _cur = curRecords[curRecords.length - 1];
      console.log("修改 _cur :>> ", _cur);
      if (_cur.parentid > 0) {
        ElMessage.warning("副规格无法编辑");
        return;
      }
      if (_cur.yw_flag == 1) {
        ElMessage.warning("已业务补充审核，无法修改");
        return;
      }
      if (_cur.flag == 1) {
        ElMessage.warning("单据已审核，不能修改");
        return;
      }

      router.push(`/mattressQuote/edit?id=${_cur.mattressid}&code=${_cur.mattresscode}`);
    }
  }),
  buttonDefault({
    label: t("common.delText"),
    power: 77,
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(77)) {
        return "你没有【报价单-删除】的使用权限";
      }

      return "";
    },
    clickFunc: item => {
      const { curRecords } = getCurrentRecords(vxeTableRef.value);

      console.log("curRecords :>> ", curRecords);
      if (!curRecords.length) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
      }

      const { userInfo } = useUserStore();
      try {
        curRecords.map(item => {
          if (item.createby !== userInfo.username && userInfo.empid != 0) {
            throw new Error("只能删除自己创建的报价单");
          }
        });
      } catch (error) {
        ElMessage.error(error.message);
        return false;
      }

      let _mattressids = curRecords.map((item: any) => Number(item.mattressid));

      ElMessageBox.confirm(`是否确定要删除${curRecords.length}张床垫报价单（及其副规格报价单）吗?`, "询问", {
        confirmButtonText: t("common.delText"),
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          DelMattress({ mattressids: _mattressids }).then(() => {
            ElMessage.success("删除成功！");

            vxeTableRef.value.refresh();
          });
        })
        .catch((e: TypeError) => {
          console.log("e :>> ", e);
          ElMessage({
            type: "info",
            message: "操作取消"
          });
        });
    }
  }),
  buttonDefault({
    label: t("common.copyQuote"),
    power: 75,
    clickFunc: item => {
      const { $table, curRecords } = getCurrentRecords(vxeTableRef.value);

      if (!curRecords.length) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
      }

      let _cur = $table.getCurrentRecord() ?? null;
      if (!_cur) {
        _cur = curRecords[curRecords.length - 1];
      }
      router.push(`/mattressQuote/copy?id=${_cur.mattressid}&code=${_cur.mattresscode}`);
    }
  }),
  // [
  buttonDefault({
    label: t("common.businessOrder"),
    power: 94,
    clickFunc: item => {
      toAuditing({ xd_flag: 1 }, t("common.businessOrder"));
    }
  }),
  buttonDefault({
    label: t("common.businessOrderCancel"),
    power: 95,
    clickFunc: item => {
      toAuditing({ xd_flag: 0 }, t("common.businessOrder"));
    }
  }),
  // ],
  // [
  buttonDefault({
    label: t("common.auditFinance"),
    power: 73,
    clickFunc: item => {
      toAuditing({ flag: 1 }, t("common.auditFinance"));
    }
  }),
  buttonDefault({
    label: t("common.withdrawAuditFinance"),
    power: 74,
    clickFunc: item => {
      toAuditing({ flag: 0 }, t("common.withdrawAuditFinance"));
    }
  }),
  // ],
  buttonDefault({
    label: t("common.copyFromMulitFlag"),
    power: 75,
    clickFunc: async item => {
      const { curRecords } = getCurrentRecords(vxeTableRef.value);

      console.log("curRecords :>> ", curRecords);
      if (!curRecords.length) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
      }

      await openDeptChoosen(curRecords);
    }
  }),
  buttonDefault({
    label: t("common.recalculateFromNotFlag"),
    power: 72,
    clickFunc: item => {
      const { curRecords } = getCurrentRecords(vxeTableRef.value);

      console.log("curRecords :>> ", curRecords);
      if (!curRecords.length) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
      }

      let list = curRecords.map((item: any) => {
        return { mattressid: Number(item.mattressid) };
      });

      ElMessageBox.confirm(`是否确定要批重算${curRecords.length}张床垫报价单吗?`, "询问", {
        confirmButtonText: t("common.okText"),
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          ReCalculateNoAudit({ list }).then(() => {
            ElMessage.success("批重算成功！");

            vxeTableRef.value.refresh();
          });
        })
        .catch((e: TypeError) => {
          console.log("e :>> ", e);
          ElMessage({
            type: "info",
            message: "操作取消"
          });
        });
    }
  }),
  buttonDefault({
    label: t("common.viewHistoricalQuotes"),
    power: 72,
    clickFunc: item => {
      alert("功能维护中!");
    }
  }),
  buttonDefault({
    label: t("common.showQuoteList"),
    power: 72,
    clickFunc: item => {
      alert("功能维护中!");
    }
  }),
  buttonDefault({
    label: t("common.dataTransmission"),
    power: 72,
    clickFunc: item => {
      alert("功能维护中!");
    }
  }),
  buttonDefault({
    label: t("common.businessSupplement"),
    power: 72,
    clickFunc: item => {
      const { $table, curRecords } = getCurrentRecords(vxeTableRef.value);

      if (!curRecords.length) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
      }
      let _cur = $table.getCurrentRecord() ?? curRecords[curRecords.length - 1];
      let type = 1;
      // router.push(`/erpapi/mattressInterface/${type}/edit?id=${_cur.mattressid}&code=${_cur.mattresscode}&type=${type}`);

      gotoErpapi(_cur, type);
    }
  }),
  buttonDefault({
    label: t("common.recalculateERPCost"),
    power: 72,
    clickFunc: async item => {
      const { curRecords } = getCurrentRecords(vxeTableRef.value);

      console.log("curRecords :>> ", curRecords);
      if (!curRecords.length) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
      }

      let list = curRecords.map((item: any) => {
        return { mattressid: Number(item.mattressid) };
      });

      ElMessageBox.confirm(`是否确定要批重算${curRecords.length}张床垫报价单吗?`, "询问", {
        confirmButtonText: t("common.okText"),
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          ReCalculateERPCost({ list }).then((res: any) => {
            ElMessage.success(res.logMsg);
            vxeTableRef.value.refresh();
          });
        })
        .catch((e: TypeError) => {
          ElMessage({
            type: "info",
            message: "操作取消"
          });
        });
    }
  })
];

const openDeptChoosen = async curRecords => {
  try {
    // let newParams = {
    //   dsname: "_Mapper_deptid",
    //   queryparams: {}
    // };
    // let res = await CommonDynamicSelect(newParams);
    // if (res.datatable) {
    //   deptEnum.value = res.datatable?.map((item: any) => {
    //     return { label: item.deptname, value: item.deptid };
    //   });
    // }
    let enumMap = vxeTableRef.value.enumMap;
    deptEnum.value = enumMap.get("deptid");
    console.log("openDeptChoosen deptEnum.value :>> ", deptEnum.value);

    if (deptEnum.value.length > 0) {
      formParam.value.deptid = curRecords[0].deptid;
      formParam.value.packtype = curRecords[0].packtype;
      formParam.value.packqty = curRecords[0].packqty;

      dialogFormVisible.value = true;
    } else {
      console.error("获取部门列表为空");
    }
  } catch (error) {
    console.error("获取部门列表失败", error);
  }
};

const BatchCopyMattressAudited = () => {
  const { curRecords } = getCurrentRecords(vxeTableRef.value);

  console.log("curRecords :>> ", curRecords);
  if (!curRecords.length) {
    ElMessage.warning(t("business.tips.mattress.records"));
    return;
  }

  let list = curRecords.map((item: any) => {
    return {
      mattressid: Number(item.mattressid),
      deptid: formParam.value.deptid,
      area: formParam.value.area,
      cabinet_type: formParam.value.cabinet_type,
      packtype: formParam.value.packtype,
      packqty: formParam.value.packqty
    };
  });
  ElMessageBox.confirm(`是否确定要批复制${curRecords.length}张床垫报价单吗?`, "询问", {
    confirmButtonText: t("common.okText"),
    cancelButtonText: "否",
    type: "warning"
  })
    .then(() => {
      CopyMattressAudited({ list }).then(() => {
        ElMessage.success("批复制成功！");
        dialogFormVisible.value = false;
        vxeTableRef.value.refresh();
      });
    })
    .catch((e: TypeError) => {
      console.log("e :>> ", e);
      ElMessage({
        type: "info",
        message: "操作取消"
      });
    });
};

/**
 * @description 监听框架属性变化
 */
mittBus.on(MittEnum.MattressList, () => {
  vxeTableRef.value.refresh();
});
</script>
