import { ref, reactive, computed, toRefs, nextTick } from "vue";
import { ColumnProps } from "@/components/LjVxeTable/interface";
import { GetSoftBedMxList } from "@/api/modules/quote";
import { ALLOW_EDIT_STATE } from "@/config/index";
import { ElButton, ElMessage, ElMessageBox, ElRow, ElCol } from "element-plus";
import { AuditSoftBedQuote, DeleteSoftBedQuote } from "@/api/modules/quote";
import { getDeptList } from "@/api/modules/saleprice";
import { CommonDynamicSelect } from "@/api/modules/common";
import SoftBedSelect from "@/views/system/selector/softbedTemplate/select.vue";
interface defaultState {
  /**
   * @description 单据当前状态
   */
  orderStatus: string;
  /**
   * @description 列表Ref
   */
  VxeTableRef: any;
  /**
   * @description 详情页Ref
   */
  LjDetailRef: any;
  /**
   * @description 详情页明细表格Ref
   */
  VxeTableMxRef: any;
  initParams: any;
  /**
   * @description 详情页主表数据
   */
  softBed: any;
  /**
   * @description 详情页主表明细数据
   */
  softBedMx: any[];
  /**
   * @description 详情页主表明细数据-床头
   */
  headBoardMx: any[];
  /**
   * @description 详情页主表明细数据-床头柜
   */
  nightStandMx: any[];
  /**
   * @description 详情页主表明细数据-床架
   */
  bedFrameMx: any[];
}

/**
 * @description 表格多选数据操作
 * @param {String} rowKey 当表格可以多选时，所指定的 id
 * */
export const useHooks = (t?: any) => {
  const state = reactive<defaultState>({
    orderStatus: "",
    VxeTableRef: null,
    LjDetailRef: null,
    VxeTableMxRef: null,
    softBed: null,
    softBedMx: null,
    headBoardMx: null,
    nightStandMx: null,
    bedFrameMx: null,
    initParams: { arg_softbed_id: 0 }
  });
  // 表格配置项
  const columns: ColumnProps<any>[] = [
    { type: "checkbox", width: 40, fixed: "left" },
    {
      field: "pid",
      title: "序",
      width: 40,
      basicinfo: {
        span: 1,
        row: 1
      }
    },
    {
      field: "softbed_code",
      title: "报价唯一码",
      basicinfo: {
        span: 1,
        row: 1,
        order: 1,
        group: "单据信息"
      }
    },
    {
      field: "deptid",
      title: "部门",
      enum: () =>
        getDeptList({}).then(res => {
          return res.datatable;
        }),
      fieldNames: { label: "deptname", value: "deptid" },
      search: {
        el: "select",
        key: "arg_deptid",
        props: {
          filterable: true,
          onChange: val => {
            state.initParams.arg_deptid = val;
          }
        },
        order: 1
      },
      basicinfo: {
        el: "select",
        span: 1,
        row: 1,
        order: 1,
        group: "单据信息",
        editable: (scope: any) => {
          if (ALLOW_EDIT_STATE.includes(scope.status) && Number(scope.searchParam.softbed_id) <= 0) {
            return true;
          }
          return false;
        },
        rules: [{ required: true, message: "请先选择部门", trigger: "change" }],
        props: {
          filterable: true,
          clearable: false,
          onChange: val => {
            wf_get_moneyrate_discount(val);
          }
        }
      }
    },
    {
      field: "is_template",
      title: "模板报价",
      datatype: "checkbox",
      basicinfo: {
        el: "checkbox",
        span: 1,
        row: 1,
        order: 2,
        group: "单据信息"
      }
    },
    {
      field: "create_date",
      title: "报价日期",
      format: "yyyy-MM-dd HH:mm",
      basicinfo: {
        span: 1,
        row: 1,
        order: 3,
        group: "单据信息"
      }
    },
    {
      field: "template_code",
      title: "模板编号",
      basicinfo: {
        span: 1,
        row: 1,
        order: 4,
        group: "单据信息",
        editable: (scope: any) => {
          if (ALLOW_EDIT_STATE.includes(scope.status) && Number(scope.searchParam.is_template)) {
            return true;
          }
          return false;
        }
      }
    },
    {
      field: "softbed_name",
      title: "报价名称",
      basicinfo: {
        el: "input",
        span: 1,
        row: 1,
        order: 5,
        group: "单据信息",
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "template_name",
      title: "模板名称",
      basicinfo: {
        span: 1,
        row: 1,
        order: 6,
        group: "单据信息",
        editable: (scope: any) => {
          if (ALLOW_EDIT_STATE.includes(scope.status) && Number(scope.searchParam.is_template)) {
            return true;
          }
          return false;
        }
      }
    },
    {
      field: "softbed_relcode",
      title: "报价编码",
      basicinfo: {
        el: "input",
        span: 1,
        row: 1,
        order: 7,
        group: "单据信息",
        editable: ALLOW_EDIT_STATE
      }
    },
    {
      field: "mtrlmode",
      title: "物料规格",
      basicinfo: {
        span: 1,
        row: 1,
        order: 8,
        group: "单据信息"
      }
    },
    {
      field: "create_emp",
      title: "报价人",
      basicinfo: {
        span: 1,
        row: 1,
        order: 9,
        group: "单据信息"
      }
    },
    {
      field: "mtrltype",
      title: "物料类别",
      basicinfo: {
        span: 1,
        row: 1,
        order: 10,
        group: "单据信息"
      }
    },
    {
      field: "has_type",
      title: "类型",
      visible: false,
      basicinfo: {
        span: 2,
        row: 1,
        order: 10,
        group: "单据信息",
        labelHidden: true,
        render: (scope: any) => {
          let _disabled = !ALLOW_EDIT_STATE.includes(state.orderStatus);
          let _type = _disabled ? "info" : "primary";
          return (
            <>
              <ElRow>
                <ElCol span={16}>
                  <el-checkbox
                    v-model={scope.searchParam.has_headboard}
                    true-value={1}
                    false-value={0}
                    disabled={_disabled}
                    label="床头"
                    class="mr-8"
                    // onChange={val => autoLoadExtraData_chai(val, "if_m_chai")}
                  />
                  <el-checkbox
                    v-model={scope.searchParam.has_nightstand}
                    true-value={1}
                    false-value={0}
                    disabled={_disabled}
                    label="床头柜"
                    class="mr-8"
                    // onChange={val => autoLoadExtraData_chai(val, "if_z_chai")}
                  />
                  <el-checkbox
                    v-model={scope.searchParam.has_bedframe}
                    true-value={1}
                    false-value={0}
                    disabled={_disabled}
                    label="床架"
                    // onChange={val => autoLoadExtraData_chai(val, "if_d_chai")}
                  />
                </ElCol>
                <ElCol span={8}>
                  <ElButton type={_type} size="small" disabled={_disabled} onClick={onOpenConfigureDialog}>
                    选择部件配置
                  </ElButton>
                </ElCol>
              </ElRow>
            </>
          );
        }
      }
    },
    {
      field: "has_headboard",
      width: 44,
      align: "center",
      title: "床头",
      basicinfo: {
        span: 1,
        row: 1,
        order: 10,
        group: "单据信息",
        visible: false
      }
    },
    {
      field: "has_nightstand",
      width: 58,
      align: "center",
      title: "床头柜",
      basicinfo: {
        span: 1,
        row: 1,
        order: 11,
        group: "单据信息",
        visible: false
      }
    },
    {
      field: "has_bedframe",
      basicinfo: {
        span: 1,
        row: 1,
        order: 12,
        group: "单据信息",
        visible: false
      },
      width: 44,
      align: "center",
      title: "床架"
    },
    {
      field: "other_rate",
      format: "cutNumber",
      basicinfo: {
        el: "input-number",
        span: 1,
        row: 1,
        order: 19,
        group: "费用信息",
        editable: ALLOW_EDIT_STATE
      },
      title: "额外点数"
    },
    {
      field: "taxes",
      title: "税金",
      format: "cutNumber",
      enum: [
        {
          label: "不含税",
          value: 1
        },
        {
          label: "含税",
          value: 1.07
        }
      ],
      basicinfo: {
        el: "select",
        span: 1,
        row: 1,
        order: 20,
        group: "费用信息",
        editable: ALLOW_EDIT_STATE,
        render: (scope: any) => {
          let optionRender = [];
          let _disabled = !ALLOW_EDIT_STATE.includes(scope.status);
          scope.enum.map(item => {
            optionRender.push(<el-option label={item.label} value={item.value} />);
          });
          let slotprefix = {
            prefix: () => {
              return <>{scope.searchParam.taxrate}</>;
            }
          };

          let _taxrate = Number(scope.searchParam.taxrate);
          return (
            <el-select
              v-model={_taxrate}
              v-slots={slotprefix}
              class="select-text-right"
              disabled={_disabled}
              onChange={val => funcTaxrateChange(val, scope.searchParam)}
            >
              {optionRender}
            </el-select>
          );
        }
      }
    },
    {
      field: "extras_cost",
      format: "cutNumber",
      basicinfo: {
        el: "input-number",
        span: 1,
        row: 1,
        order: 21,
        group: "费用信息",
        editable: ALLOW_EDIT_STATE
      },
      title: "额外费用"
    },
    {
      field: "moneyrate",
      title: "币种",
      enum: () => {
        return GetMoneyRateMapper().then(res => {
          return res.datatable;
        });
      },
      render: (scope: any) => {
        return (
          <>
            <div class="flx-justify-between">
              <span>
                <>{scope.row.moneyrate > 1 ? `美元` : "人民币"}</>
              </span>
              {scope.row.moneyrate > 1 && (
                <span>
                  <>{scope.row.moneyrate}</>
                </span>
              )}
            </div>
          </>
        );
      },
      basicinfo: {
        el: "select",
        span: 1,
        row: 1,
        order: 22,
        group: "费用信息",
        editable: ALLOW_EDIT_STATE,
        render: (scope: any) => {
          let optionRender = [];
          let _disabled = !ALLOW_EDIT_STATE.includes(scope.status);
          scope.enum.map(item => {
            optionRender.push(<el-option label={item.label} value={item.value} />);
          });
          let slotprefix = {
            prefix: () => {
              return <>{scope.searchParam.moneyrate}</>;
            }
          };

          return (
            <el-select
              v-model={scope.searchParam.if_moneyrate}
              v-slots={slotprefix}
              class="select-text-right"
              disabled={_disabled}
              onChange={val => wf_get_moneyrate_discount(val)}
            >
              {optionRender}
            </el-select>
          );
        }
      }
    },
    {
      field: "commission",
      format: "cutNumber",
      basicinfo: {
        el: "input-number",
        span: 1,
        row: 1,
        order: 23,
        group: "费用信息",
        editable: ALLOW_EDIT_STATE
      },
      title: "佣金"
    },
    {
      field: "dscrp",
      title: "备注",
      basicinfo: {
        el: "input",
        editable: ALLOW_EDIT_STATE,
        span: 1,
        row: 1,
        order: 24,
        group: "费用信息",
        props: {
          type: "textarea"
        }
      }
    },
    {
      field: "foreign_cost",
      format: "cutNumber",
      basicinfo: {
        span: 1,
        row: 1,
        order: 25,
        group: "报价信息",
        visible: true,
        ishidden: false
      },
      title: "外币价"
    },
    {
      field: "nottax_dept_cost",
      format: "cutNumber",
      basicinfo: {
        span: 1,
        row: 1,
        order: 26,
        group: "报价信息",
        visible: true,
        ishidden: false
      },
      title: "部门售价(不含税)"
    },
    {
      field: "dept_cost",
      format: "cutNumber",
      basicinfo: {
        span: 1,
        row: 1,
        order: 27,
        group: "报价信息",
        visible: true,
        ishidden: false
      },
      title: "部门含税价"
    },
    {
      field: "nottax_factory_cost",
      format: "cutNumber",
      basicinfo: {
        span: 1,
        row: 1,
        order: 28,
        group: "报价信息",
        visible: true,
        ishidden: false
      },
      title: "不含税出厂价"
    },
    {
      field: "costamt",
      format: "cutNumber",
      basicinfo: {
        span: 1,
        row: 1,
        order: 29,
        group: "报价信息",
        visible: true,
        ishidden: false
      },
      title: "报价金额"
    },
    {
      field: "bi_nottax_dept_cost",
      basicinfo: {
        span: 1,
        row: 1,
        order: 31,
        group: "成本信息",
        visible: true,
        ishidden: false
      },
      title: "财务底价"
    },
    {
      field: "total_material_cost",
      basicinfo: {
        span: 1,
        row: 1,
        order: 32,
        group: "成本信息",
        visible: true,
        ishidden: false
      },
      title: "总材料成本"
    },
    {
      field: "total_hr_cost",
      basicinfo: {
        span: 1,
        row: 1,
        order: 33,
        group: "成本信息",
        visible: true,
        ishidden: false
      },
      title: "总人力成本"
    },
    {
      field: "total_cost",
      basicinfo: {
        span: 1,
        row: 1,
        order: 34,
        group: "成本信息",
        visible: true,
        ishidden: false
      },
      title: "总成本"
    },
    {
      field: "flag",
      basicinfo: {
        span: 1,
        row: 1,
        order: 30,
        group: "其他",
        visible: true,
        ishidden: false
      },
      width: 44,
      align: "center",
      datatype: "checkbox",
      title: "审核"
    },
    {
      field: "audit_date",
      format: "yyyy-MM-dd HH:mm",
      width: 160,
      basicinfo: {
        span: 1,
        row: 1,
        order: 31,
        group: "其他",
        visible: true,
        ishidden: false
      },
      title: "审核日期",
      colorder: 26
    },
    {
      field: "audit_emp",
      basicinfo: {
        span: 1,
        row: 1,
        order: 32,
        group: "其他",
        visible: true,
        ishidden: false
      },
      title: "审核人"
    },
    {
      field: "update_date",
      format: "yyyy-MM-dd HH:mm",
      width: 160,
      basicinfo: {
        span: 1,
        row: 1,
        order: 33,
        group: "其他",
        visible: true,
        ishidden: false
      },
      title: "更新日期"
    },
    {
      field: "update_emp",
      basicinfo: {
        span: 1,
        row: 1,
        order: 34,
        group: "其他",
        visible: true,
        ishidden: false
      },
      title: "更新人"
    }
  ];
  // 明细表格配置项
  const columnsMx: ColumnProps<any>[] = [
    {
      field: "printid",
      title: "行号",
      width: 50
    },
    {
      field: "allow_edit",
      title: "业务修改",
      width: 80,
      datatype: "checkbox"
    },
    {
      field: "pzname",
      title: "部件选配项",
      visible: false
    },
    {
      field: "pznamemx",
      title: "部件选配项值",
      visible: false
    },
    {
      field: "mtrlcode",
      title: "物料编码",
      visible: false
    },
    {
      field: "mtrlname",
      title: "物料名称规格",
      width: 400,
      render: (scope: any) => {
        return `${scope.row.mtrlname} ${scope.row.mtrlmode}`;
      }
    },
    {
      field: "unit",
      title: "物料单位",
      visible: false
    },
    {
      field: "cutting_length",
      title: "下料长(mm)",
      datatype: "number"
    },
    {
      field: "cutting_width",
      title: "下料宽(mm)",
      datatype: "number"
    },
    {
      field: "cutting_qty",
      title: "下料数量",
      datatype: "number"
    },
    {
      field: "useqty",
      title: "理论用料量",
      datatype: "number"
    },
    {
      field: "use_formula",
      title: "用料量公式"
    },
    {
      field: "use_formula_str",
      title: "用料量文本公式"
    },
    {
      field: "actual_useqty",
      title: "实际用量",
      datatype: "number"
    },
    {
      field: "loss_rate",
      title: "损耗率",
      datatype: "number"
    },
    {
      field: "price",
      title: "材料单价",
      datatype: "number"
    },
    {
      field: "price_formula",
      title: "单价公式"
    },
    {
      field: "price_formula_str",
      title: "单价文本公式"
    },
    {
      field: "cost_price",
      title: "成本单价",
      datatype: "number"
    },
    {
      field: "cost_amt",
      title: "成本金额",
      datatype: "number"
    }
  ];
  /**
   * 详细页获取数据
   */
  const detail_getData = async (params: any) => {
    const result = await GetSoftBedMxList(params);
    detail_dataCallback(result);
  };

  const detail_dataCallback = (data: any) => {
    if (state.orderStatus === "new") {
      data.softbed.taxrate = 1;
    }

    state.softBed = [data.softbed];
    state.softBedMx = data.mxList;
    state.headBoardMx = data.mxList.filter(item => item.has_type === 1);
    state.nightStandMx = data.mxList.filter(item => item.has_type === 2);
    state.bedFrameMx = data.mxList.filter(item => item.has_type === 4);
  };

  /**
   * 打开部件配置弹窗
   */
  const onOpenConfigureDialog = () => {};
  /**
   * 确认部件配置项值
   * @param params 返回内容
   */
  const onConfirmConfigureDialog = (params: any) => {};
  /**
   * 保存报价
   */
  const onSave = () => {};
  /**
   * 审核报价
   */
  const onAudit = (list: any) => {
    ElMessageBox.confirm("是否确定要审核单据吗?", "询问", {
      confirmButtonText: "是",
      cancelButtonText: "否",
      type: "warning"
    })
      .then(() => {
        AuditSoftBedQuote({ list, type: 1 }).then(() => {
          ElMessage.success(t("sys.api.operationSuccess"));
          state.VxeTableMxRef.refresh();
        });
      })
      .catch((e: TypeError) => {
        ElMessage({
          type: "info",
          message: "操作取消"
        });
      });
  };
  /**
   * 撤审报价
   */
  const onCAudit = (list: any) => {
    ElMessageBox.confirm("是否确定要撤审单据吗?", "询问", {
      confirmButtonText: "是",
      cancelButtonText: "否",
      type: "warning"
    })
      .then(() => {
        AuditSoftBedQuote({ list, type: 0 }).then(() => {
          ElMessage.success(t("sys.api.operationSuccess"));
          state.VxeTableMxRef.refresh();
        });
      })
      .catch((e: TypeError) => {
        ElMessage({
          type: "info",
          message: "操作取消"
        });
      });
  };
  /**
   * 删除报价
   */
  const onDelete = (list: any, cb?: Function) => {
    ElMessageBox.confirm(`是否确定要删除${list.length}张报价单吗?`, "询问", {
      confirmButtonText: t("common.delText"),
      cancelButtonText: "否",
      type: "warning"
    })
      .then(() => {
        DeleteSoftBedQuote({ list }).then(() => {
          ElMessage.success(t("sys.api.operationSuccess"));
          cb && cb();
          state.VxeTableMxRef.refresh();
        });
      })
      .catch((e: TypeError) => {
        ElMessage({
          type: "info",
          message: "操作取消"
        });
      });
  };
  /**
   * 复制报价
   */
  const onCopyQuote = () => {};
  /**
   * 显示公式
   */
  const onShowFormula = () => {};

  const GetMoneyRateMapper = async () => {
    return CommonDynamicSelect({ dsname: "_Mapper_if_moneyrate", queryparams: {} });
  };
  /**
   * @description 获取部门汇率 和  折扣率
   */
  const wf_get_moneyrate_discount = (val: any) => {
    const { _mainData, enumMap } = state.LjDetailRef;

    let deptEnum = enumMap.get("deptid");
    console.log("deptEnum :>> ", deptEnum);
    if (deptEnum) {
      let depItem = deptEnum.find((item: any) => item.deptid == _mainData.deptid);
      if (depItem) {
        let _moneyrate = !depItem.moneyrate || Number(depItem.moneyrate) == 0 ? 1 : depItem.moneyrate;
        if (val == 0 || !_mainData.if_moneyrate) {
          _mainData.if_moneyrate = 0;
          _mainData.moneyrate = 1;
        } else {
          _mainData.moneyrate = _moneyrate;
        }
        _mainData.discount = depItem.discount;
      }
    }
  };

  const funcTaxrateChange = async (val: any, data) => {
    data.taxrate = val;
  };

  return {
    ...toRefs(state),
    columns,
    columnsMx,
    detail_getData,
    onSave,
    onAudit,
    onCAudit,
    onDelete,
    onCopyQuote,
    onShowFormula
  };
};
