import {defineComponent, onMounted, reactive, ref} from 'vue'
import styles from "@views/music-library/music-sheet/modal/index.module.less";
import {NButton, NCascader, NCheckbox, NCheckboxGroup, NForm, NFormItem, NInput, NInputNumber, NSelect, NSpace, NTabPane, NTabs, useMessage} from "naive-ui";
import {appKey, musicSheetType, musicSheetPaymentType, musicSheetAvailableType} from "@/utils/constant";
import {
  musicSheetApplicationExtendCategoryApplicationExtendInfo,
  musicSheetApplicationExtendCategoryList,
  musicSheetApplicationExtendSave,
  musicSheetDetail,
} from "@views/music-library/api";
import {getSelectDataFromObj} from "@/utils/objectUtil";

export default defineComponent({
  name: 'use-project',
  props: {
    useProject: {
      type: Array,
      required: true,
      default: []
    },
    id: {
      type: String,
      required: true,
      default: null
    }
  },
  emits: ['close', 'getList'],
  setup(props, {emit}) {
    const forms = reactive({
      musicSheetId: null,
      useApplicationIds: [] as any,

      useProjectParamConfig: {  //各个项目配置的参数
        'GYM': {
          musicSheetCategoryId: null as any,
          sortNo: null as any,
          paymentType: null as any, // 是否收费
        },
        'GYT': {
          musicSheetCategoryId: null as any,
          sortNo: null as any,
        },
        'KLX': {
          availableType: null as any, //可用途径 ORG 机构 PLATFORM 平台
          musicSheetCategoryId: null as any,
          paymentType: null as any, // 是否收费
          musicPrice: null as any, // 曲目价格
          topFlag: null as any, // 是否置顶(0:否;1:是)
          exquisiteFlag: null as any, // 精品标志
          sortNo: null as any,
        },
        'KT': {
          musicSheetCategoryId: null as any,
          sortNo: null as any,
        },


      } as any,
    })
    const state = reactive({
      loading: false,
      tabName: null as any,
      selectAppKey: [] as any, //选择的APP
      userProjectList: [] as any, // 适用项目列表
      musicSheetCategoryOptions: {} as any,//项目曲目分类选择


    })

    const btnLoading = ref(false)
    const message = useMessage()

    onMounted(async () => {
      state.loading = true

      // 加载已经配置的APP
      const {data} = await musicSheetDetail({id: props.id})
      if (data && data.musicSheetExtend) {
        forms.useApplicationIds = data.musicSheetExtend.useApplicationIds?.split(',') || []
      }

      // 加载所有的APP
      const keys = Object.keys(appKey);
      state.userProjectList = props.useProject.filter((next: any) => {
        const indexOf = keys.indexOf(next.appKey);
        return indexOf > -1;
      })
      state.userProjectList.forEach((next: any) => {
        if (forms.useApplicationIds.includes(next.id)) {
          state.selectAppKey.push(next.appKey)
        }
      })
      if (state.selectAppKey.length > 0) {
        state.tabName = state.selectAppKey[0]
      }

      // 加载不同项目的曲目分类列表
      const projectIdArr = [] as any
      const appIdCodeMap = new Map<number, string>
      props.useProject.forEach((project: any) => {
        projectIdArr.push(project.id)
        appIdCodeMap.set(project.id, project.name)
      })
      if (projectIdArr.length > 0) {
        const {data} = await musicSheetApplicationExtendCategoryList({applicationIds: projectIdArr.join(',')})
        data.forEach((next: any) => {
          const appCode = appIdCodeMap.get(next.applicationId);
          if (appCode) {
            state.musicSheetCategoryOptions[appCode] = next.musicSheetCategories
          }
        })
      }
      for (let i = 0; i < state.selectAppKey.length; i++) {
        const appKey = state.selectAppKey[i];
        // 初始化数据
        const res = await musicSheetApplicationExtendCategoryApplicationExtendInfo({musicSheetId: props.id, appKey: appKey}) as any
        if (res && res.code === 200 && res.data?.length > 0) {
          if (appKey === 'KT') {
            forms.useProjectParamConfig.KT = res.data[0]
          } else if (appKey === 'GYT') {
            forms.useProjectParamConfig.GYT = res.data[0]
          } else if (appKey === 'GYM') {
            forms.useProjectParamConfig.GYM = res.data[0]
          } else if (appKey === 'KLX') {
            forms.useProjectParamConfig.KLX = res.data[0]
          }
        }

      }


      state.loading = false
    })


    const formsRef = ref()

    const onSubmit = async () => {
      formsRef.value.validate(async (error: any) => {
        console.log(error, 'error')
        if (error) {
          return
        }
        try {
          const appKeyIdMap = new Map<string, string>;
          props.useProject.forEach((project: any) => {
            appKeyIdMap.set(project.appKey, project.id)
          })
          // 获取选择的应用项目
          const applicationExtends = [] as any
          state.selectAppKey.forEach((appKey: any) => {
            Object.keys(forms.useProjectParamConfig).forEach(key => {
              if (appKey === key) {
                const value = forms.useProjectParamConfig[key];
                applicationExtends.push({
                  ...value,
                  musicSheetId: props.id,
                  applicationId: appKeyIdMap.get(key)
                })
              }
            })
          })

          const params = {
            'musicSheetId': props.id,
            'useApplicationIds': forms.useApplicationIds.join(','),
            'applicationExtends': applicationExtends
          }
          btnLoading.value = true
          await musicSheetApplicationExtendSave(params)
          message.success('修改成功')
          emit('getList')
          emit('close')
        } catch (e) {
          console.log(e)
        }
        btnLoading.value = false
      })
    }


    return () => (
        <div>
          <NForm
              class={styles.formContainer}
              model={forms}
              ref={formsRef}
              label-placement="left"
              label-width="85"
          >
            <NFormItem
                label="适用应用"
                path="useApplicationIds"
                rule={[
                  {
                    required: true,
                    message: '请选择适用应用'
                  }
                ]}
            >
              <NCheckboxGroup
                  v-model:value={forms.useApplicationIds}
                  onUpdateValue={(value) => {
                    state.selectAppKey = []
                    state.userProjectList.forEach((next: any) => {
                      if (value.includes(next.id)) {
                        state.selectAppKey.push(next.appKey)
                      }
                    })

                    // 反勾选时，更新选中的tab
                    if (state.selectAppKey.length == 0) {
                      state.tabName = '';
                    } else {
                      state.tabName = state.selectAppKey[0]
                    }
                  }}
              >
                {state.userProjectList.map((item: any) => (
                    <NCheckbox value={item.value}>{item.label}</NCheckbox>
                ))
                }
              </NCheckboxGroup>
            </NFormItem>
            {state.selectAppKey.length > 0 && (
                <NTabs
                    type="line"
                    v-model:value={state.tabName}
                    onUpdate:value={(val: any) => {
                      state.tabName = val
                    }}
                >
                  {state.selectAppKey.includes('GYM') &&
                      <NTabPane
                          tab={appKey.GYM}
                          name='GYM'
                      >
                          <NFormItem
                              label="曲目分类"
                              path="forms.useProjectParamConfig.GYM.musicSheetCategoryId"
                          >
                              <NCascader
                                  valueField="id"
                                  labelField="name"
                                  children-field="children"
                                  placeholder="请选择分类"
                                  v-model:value={forms.useProjectParamConfig.GYM.musicSheetCategoryId}
                                  options={state.musicSheetCategoryOptions.GYM}
                                  clearable
                              />
                          </NFormItem>
                          <NFormItem
                              label="是否收费"
                              path="forms.useProjectParamConfig.GYM.paymentType"
                          >
                              <NSelect
                                  clearable
                                  options={getSelectDataFromObj(musicSheetPaymentType)}
                              >
                              </NSelect>
                          </NFormItem>
                          <NFormItem
                              label="排序值"
                              path="musicSheetType"
                          >
                              <NInput></NInput>
                          </NFormItem>
                      </NTabPane>
                  }
                  {state.selectAppKey.includes('GYT') &&
                      <NTabPane
                          tab={appKey.GYT}
                          name='GYT'
                      >
                          <NFormItem
                              label="分类"
                              path="useProjectParamConfig.GYT.musicSheetCategoryId"
                          >
                              <NCascader
                                  valueField="id"
                                  labelField="name"
                                  children-field="children"
                                  placeholder="请选择分类"
                                  v-model:value={forms.useProjectParamConfig.GYT.musicSheetCategoryId}
                                  options={state.musicSheetCategoryOptions.GYT}
                                  clearable
                              />
                          </NFormItem>
                          <NFormItem
                              label="排序值"
                              path="useProjectParamConfig.GYT.sortNo"
                          >
                              <NInputNumber
                                  v-model:value={forms.useProjectParamConfig.KT.sortNo}
                                  placeholder="请输入排序值"
                                  clearable
                                  min={0}
                                  style={{width: '100%'}}
                              />
                          </NFormItem>
                      </NTabPane>
                  }
                  {state.selectAppKey.includes('KLX') &&
                      <NTabPane
                          tab={appKey.KLX}
                          name='KLX'
                      >
                          <NFormItem
                              label="可用途径"
                              path="musicSheetType"
                          >
                              <NSelect
                                  clearable
                                  options={getSelectDataFromObj(musicSheetAvailableType)}
                              >
                              </NSelect>
                          </NFormItem>
                          <NFormItem
                              label="曲目标签"
                              path="musicSheetType"
                          >
                              <NSelect>
                              </NSelect>
                          </NFormItem>
                          <NFormItem
                              label="是否收费"
                              path="useProjectParamConfig.KLX.paymentType"
                          >
                              <NSelect
                                  clearable
                                  options={[
                                    {
                                      label: '是',
                                      value: 1
                                    },
                                    {
                                      label: '否',
                                      value: 0
                                    }
                                  ]}
                              >
                              </NSelect>
                          </NFormItem>
                          <NFormItem
                              label="曲目价格"
                              path="useProjectParamConfig.KLX.musicPrice"
                          >
                              <NInputNumber style={"width:100%"}>

                              </NInputNumber>
                          </NFormItem>
                          <NFormItem
                              label="是否置顶"
                              path="musicSheetType"
                          >
                              <NSelect
                                  clearable
                                  options={[
                                    {
                                      label: '是',
                                      value: 1
                                    },
                                    {
                                      label: '否',
                                      value: 0
                                    }
                                  ]}
                              >
                              </NSelect>
                          </NFormItem>
                          <NFormItem
                              label="精品乐谱"
                              path="useProjectParamConfig.KLX.exquisiteFlag"
                          >
                              <NSelect
                                  clearable
                                  options={[
                                    {
                                      label: '是',
                                      value: 1
                                    },
                                    {
                                      label: '否',
                                      value: 0
                                    }
                                  ]}
                              >
                              </NSelect>
                          </NFormItem>
                          <NFormItem
                              label="排序值"
                              path="useProjectParamConfig.KLX.sortNo"
                          >
                              <NInputNumber style={"width:100%"}>

                              </NInputNumber>
                          </NFormItem>
                      </NTabPane>
                  }
                  {state.selectAppKey.includes('KT') &&
                      <NTabPane
                          tab={appKey.KT}
                          name='KT'
                      >
                          <NFormItem
                              label="曲目分类"
                              path="useProjectParamConfig.KT.musicSheetCategoryId"
                          >
                              <NCascader
                                  valueField="id"
                                  labelField="name"
                                  children-field="children"
                                  placeholder="请选择分类"
                                  v-model:value={forms.useProjectParamConfig.KT.musicSheetCategoryId}
                                  options={state.musicSheetCategoryOptions.KT}
                                  clearable
                              />
                          </NFormItem>
                          <NFormItem
                              label="排序值"
                              path="useProjectParamConfig.KT.sortNo"
                          >
                              <NInputNumber
                                  v-model:value={forms.useProjectParamConfig.KT.sortNo}
                                  placeholder="请输入排序值"
                                  clearable
                                  min={0}
                                  style={{width: '100%'}}
                              />
                          </NFormItem>
                      </NTabPane>
                  }
                </NTabs>
            )}
          </NForm>
          <NSpace justify="end" style={'margin-top: 10px'}>
            <NButton type="default" onClick={() => emit('close')}>
              取消
            </NButton>
            <NButton
                type="primary"
                onClick={() => onSubmit()}
                loading={btnLoading.value}
                disabled={btnLoading.value}
            >
              确认
            </NButton>
          </NSpace>
        </div>
    )
  }
})
