import {defineComponent, onMounted, reactive, ref} from "vue";
import {NButton, NForm, NFormItem, NInputNumber, NSelect, NSpace, useMessage} from "naive-ui";
import {musicSheetApplicationExtendCategoryApplicationExtendInfo, musicSheetApplicationExtendUpdate} from "@views/music-library/api";
import {getSelectDataFromObj} from "@/utils/objectUtil";
import {musicSheetAvailableType, musicSheetPaymentType, scoreType} from "@/utils/constant";
import {formatTree} from "@views/music-library/musicUtil";

export default defineComponent({
  name: 'project-music-cooleshow-edu-updateMusic',
  props: {
    appId: {
      type: String,
      required: true
    },
    rowData: {
      type: Object,
      required: true
    },
    musicSheetTagList: {
      type: Array,
      default: () => []
    }
  },
  emits: ['close', 'getList'],
  setup(props, {slots, attrs, emit}) {
    const message = useMessage()
    const btnLoading = ref(false)
    const forms = reactive({
      musicTagIds: [] as any,
      sortNo: null as any,
      paymentType: [] as any,
      musicPrice: null as any,
      availableType: null as any,
      topFlag: null as any,
      exquisiteFlag: null as any,
      isConvertibleScore: null as any,//是否支持转简谱
      scoreType: null as any,//默认谱面
    })
    const formsRef = ref()

    const state = reactive({
      rowData: null as any,
      musicSheetTagList: [] as any,
    })

    onMounted(async () => {
      state.rowData = props.rowData
      state.musicSheetTagList = props.musicSheetTagList
      state.musicSheetTagList.map((item: any) => {
        item.disabled = !item.enable
      })
      const {data} = await musicSheetApplicationExtendCategoryApplicationExtendInfo({musicSheetId: state.rowData.id, applicationId: props.appId}) as any
      if (!data) {
        message.error("加载应用失败")
        return
      }
      forms.musicTagIds = data[0].musicTagIds?.split(',')
      forms.sortNo = data[0].sortNo
      forms.paymentType = data[0].paymentType?.split(',')
      forms.musicPrice = data[0].musicPrice
      forms.availableType = data[0].availableType
      forms.topFlag = data[0].topFlag
      forms.exquisiteFlag = data[0].exquisiteFlag
      forms.isConvertibleScore = data[0].isConvertibleScore
      forms.scoreType = data[0].scoreType
    })

    const onSubmit = async () => {
      formsRef.value.validate(async (error: any) => {
        if (error) return false
        btnLoading.value = true
        try {
          const res = await musicSheetApplicationExtendUpdate(
              {
                ...forms,
                musicSheetId: state.rowData.id,
                musicTagIds: forms.musicTagIds.join(','),
                paymentType: forms.paymentType.join(','),
                applicationId: props.appId
              }
          ) as any;
          if (res && res.code === 200) {
            emit('close')
            emit('getList')
          }
        } catch (error) {
        }
        btnLoading.value = false
      })
    }

    return () => {
      return (
          <div style="background: #fff; padding-top: 12px">
            <NForm
                ref={formsRef}
                labelPlacement="top"
                model={forms}
                label-placement="left"
                label-width="auto"
            >
              <NFormItem
                  label="曲目标签"
                  path="musicTagIds"
                  rule={[
                    {
                      required: true,
                      message: '请选择曲目标签'
                    }
                  ]}
              >
                <NSelect
                    multiple
                    placeholder="请选择曲目标签"
                    options={state.musicSheetTagList}
                    v-model:value={forms.musicTagIds}
                    clearable
                />
              </NFormItem>

              <NFormItem
                  label="收费方式"
                  path="paymentType"
                  rule={[
                    {
                      required: true,
                      message: '请选择收费方式'
                    }
                  ]}
              >
                <NSelect
                    placeholder="请选择收费方式"
                    options={getSelectDataFromObj(musicSheetPaymentType)}
                    v-model:value={forms.paymentType}
                    multiple
                    onUpdate:value={() => {
                      const free = 'FREE'
                      if (forms.paymentType[forms.paymentType.length - 1] == free) {
                        forms.paymentType = [free]
                      } else if (forms.paymentType.length > 1 && forms.paymentType.includes(free)) {
                        forms.paymentType.splice(forms.paymentType.indexOf(free), 1)
                      }
                      if (!forms.paymentType.includes("CHARGE")) {
                        forms.musicPrice = 0
                      }
                    }}
                    clearable
                />
              </NFormItem>

              {forms.paymentType.includes('CHARGE') && (
                  <NFormItem
                      label="曲目价格"
                      path="musicPrice"
                      rule={[
                        {
                          required: true,
                          message: '请输入曲目价格'
                        }
                      ]}
                  >
                    <NInputNumber
                        style={'width:100%'}
                        placeholder="请输入曲目价格"
                        v-model:value={forms.musicPrice}
                        clearable
                    />
                  </NFormItem>
              )}
              <NFormItem
                  label="可用途径"
                  path="availableType"
                  rule={[
                    {
                      required: true,
                      message: '请选择可用途径'
                    }
                  ]}
              >
                <NSelect
                    placeholder="请选择可用途径"
                    options={getSelectDataFromObj(musicSheetAvailableType)}
                    v-model:value={forms.availableType}
                    clearable
                />
              </NFormItem>
              <NFormItem
                  label="是否置顶"
                  path="topFlag"
                  rule={[
                    {
                      required: true,
                      message: '请选择是否置顶'
                    }
                  ]}
              >
                <NSelect
                    placeholder="请选择是否置顶"
                    options={[
                      {
                        label: '是',
                        value: true
                      },
                      {
                        label: '否',
                        value: false
                      }
                    ] as any}
                    v-model:value={forms.topFlag}
                    clearable
                />
              </NFormItem>
              <NFormItem
                  label="是否精品"
                  path="exquisiteFlag"
                  rule={[
                    {
                      required: true,
                      message: '请选择是否精品'
                    }
                  ]}
              >
                <NSelect
                    placeholder="请选择是否精品"
                    options={[
                      {
                        label: '是',
                        value: true
                      },
                      {
                        label: '否',
                        value: false
                      }
                    ] as any}
                    v-model:value={forms.exquisiteFlag}
                    clearable
                />
              </NFormItem>
              <NFormItem
                  label="默认谱面"
                  path="scoreType"
                  rule={[
                    {
                      required: true,
                      message: '请选择默认谱面'
                    }
                  ]}
              >
                <NSelect
                    v-model:value={forms.scoreType}
                    placeholder="请选择默认谱面"
                    options={getSelectDataFromObj(scoreType)}
                    clearable
                />
              </NFormItem>
              <NFormItem
                  label="支持转谱"
                  path="isConvertibleScore"
                  rule={[
                    {
                      required: true,
                      message: '请选择是否支持转谱',
                      trigger: ['input', 'blur'],
                      type: 'boolean'
                    }
                  ]}
              >
                <NSelect
                    v-model:value={forms.isConvertibleScore}
                    options={
                      [
                        {
                          label: '是',
                          value: true
                        },
                        {
                          label: '否',
                          value: false
                        }
                      ] as any
                    }
                    placeholder="请选择是否支持转谱"
                    onUpdateValue={async (value: any) => {
                      if (!value) {
                        //如果不支持，修改默认谱面
                        // forms.scoreType = 'STAVE'
                      }
                    }}
                    clearable
                ></NSelect>
              </NFormItem>
              <NFormItem
                  label="排序值"
                  path="sortNo"
                  rule={[
                    {
                      required: true,
                      message: '请输入排序值'
                    }
                  ]}
              >
                <NInputNumber
                    v-model:value={forms.sortNo}
                    placeholder="请输入排序值"
                    clearable
                    min={0}
                    max={9999}
                    style={{width: '100%'}}
                />
              </NFormItem>
            </NForm>

            <NSpace justify="end">
              <NButton onClick={() => emit('close')}>取消</NButton>
              <NButton type="primary" onClick={onSubmit}
                       loading={btnLoading.value}
                       disabled={btnLoading.value}
              >
                保存
              </NButton>
            </NSpace>
          </div>
      )
    }
  }
})