<template>
  <SysDialog
    custom-class="customer-proportion-copy"
    :visible="dialog.visible"
    v-bind="getBindValue"
    :confirm-loading="dialog.confirmLoading"
    @onClose="onclose"
    @onConfirm="onconfirm"
  >
    <template #content>
      <div>
        <div class="prompt">
          <el-alert
            v-if="isPromptText"
            type="warning"
            show-icon
            :closable="false"
          >
            <div class="prompt-text">
              <div>是否确定将费用</div>
              <p class="source-text">{{ promptText.sourceText }}</p>
              <div>拷贝到:</div>
              <p class="target-text">{{ promptText.targetText }}</p>
              <div>原数据将被覆盖!</div>
            </div>
          </el-alert>
        </div>
        <!-- 列表数据 -->
        <VxeBasicTable
          ref="proportionCopyGridRef"
          v-bind="proportionCopyGridOptions"
        >
          <template #default_feeItemId="{ row }">
            {{ feeItemFindName(row.feeItemId, feeItemLists) }}
          </template>
          <!-- 数据类型 -->
          <template #edit_copyDataType="scoped">
            <vxe-select v-model="scoped.row.copyDataType" @change="changeCopyDataType(scoped)" transfer>
              <vxe-option v-for="item in copyDataTypeList" :key="item.value" :value="item.value" :label="item.label"></vxe-option>
            </vxe-select>
          </template>
          <template #default_copyDataType="{ row }">
            {{ getCopyDataType(row.copyDataType) }}
          </template>
          <!-- 比例 -->
          <template #edit_ProportionValue="scoped">
            <vxe-input
              v-model="scoped.row.proportionValue"
              v-clear-only-regex="/^\d*\.?\d{0,3}$/"
              type="text"
              class="proportion-value"
              @change="proportionCopyStatus(scoped)"
            />
          </template>
        </VxeBasicTable>
      </div>
    </template>
  </SysDialog>
</template>
<script lang="ts" setup>
import SysDialog from "@/components/SysDialog.vue";
import useDialog from "@/hooks/useDialog";
import {
  BasicTableProps,
  VxeBasicTable,
  VxeGridInstance,
  VxeTablePropTypes,
} from "@/components/VxeTable/index";
import { ref, reactive, unref, computed, nextTick } from "vue";
import { useVxeGridHanleHooks } from "@/components/VxeTable/hooks";
import { api_GetCustomerFeeSetByPId } from "@/api/customerfee/customerfeeset";
import { useMessage } from "@/hooks/useMessage";
import { isArrayLength } from "@/utils/is";
import { feeItemFindName } from "@/utils/feeSeting/data";
import { useDropDownData } from "@/hooks/useDropDownData";
import { CopyParam } from "@/api/customerfee/CustomerFeeSetModel";

const emit = defineEmits(["onConfirmProportionCopy"]);
//弹框属性
const { dialog, onClose, onShow, setLoading } = useDialog();
const getBindValue = reactive({
  title: "按比例拷贝",
  top: "5vh",
  width: 720,
  height: 0,
  overflowHidden: true,
});
const proportionCopyGridRules = reactive<VxeTablePropTypes.EditRules>({
  proportionValue: [{ required: true, message: "请输入比例" }],
  copyDataType: [{ required: true, message: "请选择数据类型" }],
});
const proportionCopyGridOptions = reactive<BasicTableProps>({
  id: "proportion_copy_table",
  border: true,
  keepSource: true,
  showOverflow: true,
  loading: false,
  rowConfig: { isHover: true },
  columnConfig: { resizable: false },
  editConfig: {
    trigger: "click",
    mode: "row",
  },
  editRules: proportionCopyGridRules,
  columns: [
    {
      field: "feeItemId",
      title: "费用类型",
      minWidth: 160,
      slots: { default: "default_feeItemId" },
    },
    {
      field: "copyDataType",
      title: "数据类型",
      width: 160,
      editRender: {},
      slots: { edit: "edit_copyDataType", default: 'default_copyDataType' },
    },
    {
      field: "proportionValue",
      title: "折扣",
      width: 160,
      editRender: {
        autofocus: ".proportion-value .vxe-input--inner",
        autoselect: true,
      },
      slots: { edit: "edit_ProportionValue" },
    },
  ],
  data: [],
});
const proportionCopyGridRef = ref<VxeGridInstance>();
const { updateStatus: proportionCopyStatus } = useVxeGridHanleHooks(
  proportionCopyGridRef
);
// 参数
const customerProportionCopyParam = reactive<CopyParam>({
  id: "",
  targetIds: [],
  feeItemCopyProportionList: [],
});
const { storeDropDownData, feeItemLists, copyDataTypeList } = useDropDownData();

enum CopyDataType {
  /**
   * 按比例
   */
  PROPORTION = 0,
  /**
  * 按数值
  */
  NUMERICAL = 1
}
// 数据类型 => 初始化值
const changeCopyDataType = (scoped) => {
  switch (scoped.row.copyDataType) {
    case CopyDataType.PROPORTION:
      scoped.row.proportionValue = '100'
      break;
    case CopyDataType.NUMERICAL:
      scoped.row.proportionValue = ''
      break;
  }
  proportionCopyStatus(scoped)
}
const getCopyDataType = (copyDataType) => {
  const findObj = unref(copyDataTypeList).find(item => item.value === copyDataType)
  if (findObj) return findObj.label
  return ''
}
const { createMessage } = useMessage();
const initLoadData = async (id: string) => {
  if (!id) {
    createMessage.error("缺少id数据！");
    return;
  }
  try {
    proportionCopyGridOptions.loading = true;
    customerProportionCopyParam.id = id;
    const feeRes = await api_GetCustomerFeeSetByPId({ id });
    if (feeRes.code !== 200) return;
    const feeItemComputeList = feeRes.data.feeItemComputeList;
    if (isArrayLength(feeItemComputeList)) {
      const list = feeItemComputeList.map((item) => ({
        feeItemId: item.feeItemId,
        copyDataType: CopyDataType.PROPORTION,
        proportionValue: 100,
      }));
      proportionCopyGridOptions.data = list;
    }
  } finally {
    proportionCopyGridOptions.loading = false;
  }
};

const promptText = ref();
const isPromptText = computed(
  () => unref(promptText) && Object.keys(unref(promptText)).length > 0
);
// 显示、隐藏
const show = (id: string, targetIds: string[], textObj) => {
  storeDropDownData.addCopyDataTypeList()
  promptText.value = textObj;
  if (isArrayLength(targetIds))
    customerProportionCopyParam.targetIds = targetIds;
  initLoadData(id);
  onShow();
};
const onclose = () => {
  customerProportionCopyParam.id = "";
  customerProportionCopyParam.targetIds = [];
  customerProportionCopyParam.feeItemCopyProportionList = [];
  proportionCopyGridOptions.data = [];
  unref(proportionCopyGridRef)?.clearValidate();
  nextTick(() => {
    onClose();
  });
};
// 提交
const onconfirm = async () => {
  const $table = proportionCopyGridRef.value;
  const getValidate = await $table?.validate(true);
  if (!!getValidate) return;
  const dataList =
    proportionCopyGridOptions.data?.map((item) => ({
      feeItemId: item.feeItemId,
      copyDataType: item.copyDataType,
      proportionValue: item.proportionValue,
    })) || [];
  if (isArrayLength(dataList))
    customerProportionCopyParam.feeItemCopyProportionList = dataList;
  setLoading(true);
  emit(
    "onConfirmProportionCopy",
    customerProportionCopyParam,
    onclose,
    setLoading
  );
};

//父组件调用子组件显示弹框
//暴露出去给外部使用
defineExpose({
  show,
});
</script>
<style lang="scss">
.customer-proportion-copy {
  .prompt {
    margin-bottom: 8px;
    .prompt-text {
      font-size: 14px;
      color: #000 !important;
      p {
        margin: 5px 0;
      }
      .source-text {
        color: #ff0000;
      }
      .target-text {
        color: #67c23a;
      }
    }
  }

  .el-dialog__footer {
    position: sticky;
    bottom: 0;
    background-color: #ffffff;
    z-index: 99;
  }
}
</style>
