import { useEditor } from "@/modules/editor";
import { useResource } from "@/modules/resource";
import { PlusOutlined } from "@ant-design/icons-vue";
import { Button, Divider, Select } from "ant-design-vue";
import { queenApi } from "queenjs";
import { defineComponent } from "vue";
import { any } from "vue-types";

export default defineComponent({
  props: {
    otherProps: any(),
  },
  emits: ["change"],
  setup(props, { emit }) {
    const { helper, controls } = useEditor();

    const resource = useResource();

    const addMusic = async () => {
      const { successRow, failRow } =
        await resource.actions.createAudioMaterial();
      if (failRow.length > 0) {
        queenApi.messageError(
          `${failRow.length}条数据上传失败，超过限制大小。`
        );
      }
      if (successRow.length > 0) {
        queenApi.messageSuccess("上传成功");
        const ctrl = resource.controls.materialAudioListCtrl;
        await ctrl.loadPage(1, 1);
        if (ctrl.state.list.length > 0) {
          const item: any = ctrl.state.list[0];
          const fileUrl = item.file.url;
          const option = {
            label: "自定义",
            value: "custom",
            src: fileUrl,
          };
          const options = [...controls.mediaCtrl.state.musicOptions];
          const customIndex = options.findIndex((e) => {
            return e.value == "custom";
          });
          if (customIndex != -1) {
            options.splice(customIndex, 1, option);
          } else {
            options.push(option);
          }
          controls.mediaCtrl.setMusicOptions(options);
          emit("change", "custom");
        }
      }
    };
    return () => {
      const { musicOptions } = controls.mediaCtrl.state;
      const compMusic = helper.findRootComp()?.value.music || "";
      const curValue = musicOptions.find((e: any) => {
        return e.value == compMusic;
      });
      return (
        <Select
          class={"w-full flex-1 overflow-hidden"}
          defaultValue={""}
          options={musicOptions}
          value={curValue?.value || ""}
          onChange={(value: any) => {
            emit("change", value);
          }}
        >
          {{
            dropdownRender: ({ menuNode }: any) => {
              return (
                <>
                  {menuNode}
                  <Divider style={{ margin: 0 }} />
                  <Button
                    type="link"
                    icon={<PlusOutlined />}
                    onMousedown={(e) => {
                      e.stopPropagation();
                    }}
                    onClick={addMusic}
                  >
                    自定义音乐
                  </Button>
                </>
              );
            },
          }}
        </Select>
      );
    };
  },
});
