import { defineComponent, ref, watchEffect, nextTick, computed } from "vue";
import { httpUnTag } from "/@/api/parameter/tagManage";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import SingleVue from "/@/components/ImageUpload/src/single.vue";
import { useAsync } from "/@/hooks/core/useAsync";
import { UnitInput } from "/@/components/Input";

import {
  ElButton,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElOption,
  ElPopconfirm,
  ElSelect,
  ElTooltip,
  ElMessage
} from "element-plus";

const defaultFormData = {
  tag_id: "",
  code: "",
  total_fee: 0,
  tag_remark: "",
  tag_img: ""
};

const props = {
  tagProps: {
    type: Object as PropType<Record<string, string>>
  },
  row: {
    type: Object as PropType<Record<string, string>>
  },
  isPay: {
    type: Boolean
  }
};

const MAP = [
  {
    value: "1",
    label: "付款"
  },
  {
    value: "2",
    label: "回票"
  },
  {
    value: "3",
    label: "回款"
  },
  {
    value: "4",
    label: "开票"
  }
];

const coinIconTypes = ["1", "3"];

const ActionUnTag = defineComponent({
  name: "ActionTag",
  props,
  emits: ["reload"],
  setup(props, { emit }) {
    const visible = ref(false);
    const formRef = ref<InstanceType<typeof ElForm>>(null);
    const formData = ref({ ...defaultFormData });

    const { run: addtagRun, loading: addtagLoading } = useAsync({
      success: () => {
        ElMessage.success('标签解除成功!')
        visible.value = false;
        emit("reload");
      }
    });

    const onAddTagWithCode = () => {
      const { row } = props;
      const { tagProps } = props;
      const { type } = tagProps;

      addtagRun(
        httpUnTag({ logid: type === "1" ? row.pay_tag_id : row.inv_tag_id })
      );
    };

    const title = computed(() => {
      const { tagProps } = props;
      const { type } = tagProps;
      if (!type) return;
      return MAP.find(s => s.value === type)?.label;
    });

    watchEffect(() => {
      if (visible.value) formData.value = { ...defaultFormData };
      nextTick(() => formRef.value && formRef.value.clearValidate());
    });

    return () => (
      <ElPopconfirm
        v-loading={addtagLoading.value}
        placement="top"
        title={`确认解除${title.value}标签?`}
        onConfirm={onAddTagWithCode}
        v-slots={{
          reference: () => (
            <ElTooltip placement="top" content={`解除${title.value}标签`}>
              <ElButton
                link
                class="reset-margin"
                type="default"
                onClick={onAddTagWithCode}
                icon={useRenderIcon(
                  coinIconTypes.includes(props.tagProps.type) ? "coin" : "stamp"
                )}
              />
            </ElTooltip>
          )
        }}
      />
    );
  }
});

export default ActionUnTag;
