import { defineComponent, ref, watchEffect, nextTick, computed } from "vue";
import { httpBillAddTag, httpList } from "../../../../../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,
  ElSelect,
  ElTooltip
} 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 ActionTag = 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 {
      data: taglist,
      run: taglistRun,
      loading: taglistLoading
    } = useAsync({
      initalData: [],
      isList: true
    });

    const requesetTaglist = async () => {
      const { type } = props.tagProps;

      const params = {
        type,
        size: 1000
      };

      taglistRun(httpList(params));
    };

    const { run: addtagRun, loading: addtagLoading } = useAsync({
      success: () => {
        visible.value = false;
        emit("reload");
      }
    });

    const onAddTagWithCode = () => {
      formRef.value.validate(isValid => {
        if (!isValid) return;
        const { tag_id, total_fee, tag_img, tag_remark } = formData.value;
        const { row, tagProps } = props;
        const { prop } = tagProps;

        addtagRun(
          httpBillAddTag({
            tag_id,
            total_fee: String(total_fee),
            code: row[prop],
            tag_img,
            tag_remark
          })
        );
      });
    };

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

    function renderModal() {
      return (
        <ElDialog
          closeOnClickModal={false}
          title={`添加${title.value}标签`}
          appendToBody
          center
          v-model={visible.value}
          onOpen={() => requesetTaglist()}
        >
          <ElForm model={formData.value} ref={formRef} labelWidth="100px">
            <ElFormItem
              prop="tag_id"
              label="标签名:"
              rules={[
                {
                  message: "请选择标签名",
                  required: true,
                  trigger: "change"
                }
              ]}
            >
              <ElSelect
                class="w-full"
                v-model={formData.value.tag_id}
                loading={taglistLoading.value}
                placeholder="请选择标签名"
                filterable
              >
                {taglist.value.map(tag => (
                  <ElOption key={tag.id} label={tag.tag_name} value={tag.id} />
                ))}
              </ElSelect>
            </ElFormItem>

            <ElFormItem
              prop="total_fee"
              label="标签金额:"
              rules={[
                {
                  message: "请输入标签金额",
                  required: true,
                  trigger: "change"
                }
              ]}
            >
              <UnitInput
                style={{ width: "100%" }}
                v-model={formData.value.total_fee}
              />
            </ElFormItem>

            <ElFormItem
              label="标签标注"
              prop="tag_remark"
              v-show={props.tagProps.type === "2"}
            >
              <ElInput
                placeholder="请输入标签标注"
                v-model={formData.value.tag_remark}
              />
            </ElFormItem>

            <ElFormItem label="标签图片">
              <SingleVue v-model={formData.value.tag_img} />
            </ElFormItem>

            <div class="w-full flex justify-end flex-end">
              <ElButton
                size="small"
                type="primary"
                onClick={() => onAddTagWithCode()}
                loading={addtagLoading.value}
              >
                添加
              </ElButton>
            </div>
          </ElForm>
        </ElDialog>
      );
    }

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

    return () => (
      <ElTooltip placement="top" content={`添加${title.value}标签`}>
        <ElButton
          link
          class="reset-margin"
          type="primary"
          onClick={() => (visible.value = true)}
          icon={useRenderIcon(
            coinIconTypes.includes(props.tagProps.type) ? "coin" : "stamp"
          )}
        >
          {renderModal()}
        </ElButton>
      </ElTooltip>
    );
  }
});

export default ActionTag;
