import { computed, defineComponent, nextTick, onMounted, reactive, ref } from 'vue'
import styles from '@views/music-library/music-sheet/modal/index.module.less'
import {
  NButton,
  NCascader,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NInputNumber,
  NSelect,
  NSpace,
  NTabPane,
  NTabs,
  useMessage
} from 'naive-ui'
import { appKey, musicSheetAvailableType, musicSheetPaymentType } 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 tabsRef = ref()
    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 gymFileRequire = computed(() => {
      const app = forms.useProjectParamConfig.GYM
      const fieldList = ['musicSheetCategoryId', 'paymentType']
      for (let i = 0; i < fieldList.length; i++) {
        const fieldValue = app[fieldList[i]]
        if (fieldValue) {
          return true
        }
      }
      return false
    })

    const klxFileRequire = computed(() => {
      const app = forms.useProjectParamConfig['KLX']
      const fieldList = [
        'availableType',
        'musicSheetCategoryId',
        'paymentType',
        'musicPrice',
        'topFlag',
        'exquisiteFlag'
      ]
      for (let i = 0; i < fieldList.length; i++) {
        const fieldValue = app[fieldList[i]]
        if (fieldValue) {
          return true
        }
      }
      return false
    })

    const ktFileRequire = computed(() => {
      const app = forms.useProjectParamConfig['KT']
      const fieldList = ['musicSheetCategoryId']
      for (let i = 0; i < fieldList.length; i++) {
        const fieldValue = app[fieldList[i]]
        if (fieldValue) {
          return true
        }
      }
      return false
    })

    const gytFileRequire = computed(() => {
      const app = forms.useProjectParamConfig['GYT']
      const fieldList = ['musicSheetCategoryId']
      for (let i = 0; i < fieldList.length; i++) {
        const fieldValue = app[fieldList[i]]
        if (fieldValue) {
          return true
        }
      }
      return false
    })

    const state = reactive({
      loading: false,
      musicSheetData: null as any,
      tabName: null as any,
      selectAppKey: [] as any, //选择的APP
      selectAppName: [] as any, //app key name映射
      appKeyNameMap: null as any, //
      userProjectList: [] as any, // 适用项目列表
      musicSheetCategoryOptions: {} as any, //项目曲目分类选择

      musicSheetCanBeUsedProjectKey: [] as any //  曲目可以使用在哪些项目，通过声部配置过滤
    })

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

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

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

      // 查询该曲目可以使用的app
      // {
      //   try {
      //     const {data} = await musicSheetApplicationApplicationInfo(state.musicSheetData.id)
      //     data.forEach((next: any) => {
      //       state.musicSheetCanBeUsedProjectKey.push(next.appKey)
      //     })
      //   } catch (e) {
      //   }
      // }

      // 加载所有的APP
      const keys = Object.keys(appKey)
      // state.userProjectList = props.useProject.filter((next: any) => {
      //   const indexOf = keys.indexOf(next.appKey);
      //   return indexOf > -1;
      // })

      props.useProject.forEach((next: any) => {
        const indexOf = keys.indexOf(next.appKey)
        let disabled = false
        if (indexOf > -1) {
          // disabled = !state.musicSheetCanBeUsedProjectKey.includes(next.appKey);
          state.userProjectList.push({
            ...next,
            disabled: disabled
          })
        }
      })

      state.appKeyNameMap = new Map<String, String>()
      state.userProjectList.forEach((next: any) => {
        if (forms.useApplicationIds.includes(next.id)) {
          state.selectAppKey.push(next.appKey)
        }
        state.appKeyNameMap.set(next.appKey, next.appName)
      })
      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.appKey)
      })
      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
          }
        })
      }
      {
        const { data } = (await musicSheetApplicationExtendCategoryApplicationExtendInfo({
          musicSheetId: props.id
        })) as any
        data.forEach((next: any) => {
          const key = next.appKey
          if (key === 'GYM') {
            forms.useProjectParamConfig[key]['musicSheetCategoryId'] = next.musicSheetCategories
            forms.useProjectParamConfig[key]['sortNo'] = next.sortNo
            forms.useProjectParamConfig[key]['paymentType'] = next.paymentType
          } else if (key === 'GYT') {
            forms.useProjectParamConfig[key]['musicSheetCategoryId'] = next.musicSheetCategoryId
            forms.useProjectParamConfig[key]['sortNo'] = next.sortNo
          } else if (key === 'KLX') {
            forms.useProjectParamConfig[key]['availableType'] = next.availableType
            forms.useProjectParamConfig[key]['musicSheetCategoryId'] = next.musicSheetCategoryId
            forms.useProjectParamConfig[key]['paymentType'] = next.paymentType
            forms.useProjectParamConfig[key]['musicPrice'] = next.musicPrice
            forms.useProjectParamConfig[key]['topFlag'] = next.topFlag
            forms.useProjectParamConfig[key]['exquisiteFlag'] = next.exquisiteFlag
            forms.useProjectParamConfig[key]['sortNo'] = next.sortNo
          } else if (key === 'KT') {
            forms.useProjectParamConfig[key]['musicSheetCategoryId'] = next.musicSheetCategoryId
            forms.useProjectParamConfig[key]['sortNo'] = next.sortNo
          }
          // forms.useProjectParamConfig[key] = next
        })
      }

      state.loading = false
    })

    const formsRef = ref()

    const onSubmit = async () => {
      formsRef.value.validate(async (error: any) => {
        if (error) {
          if (Array.isArray(error) && error.length > 0) {
            const app = error[0][0].field?.split('.')[1]
            if (app && state.selectAppKey.includes(app)) {
              state.tabName = app
            }
          }
          return
        }
        btnLoading.value = true
        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]
                if (!value['sortNo']) {
                  value['sortNo'] = 0
                }
                //除了排序号，其他字段都不为空时才保存数据
                const every = Object.values(value).every((val: any) => {
                  return !(val === null || val === undefined || val === '')
                })
                if (every) {
                  applicationExtends.push({
                    ...value,
                    musicSheetId: props.id,
                    applicationId: appKeyIdMap.get(key)
                  })
                }
              }
            })
          })

          const params = {
            musicSheetId: props.id,
            useApplicationIds: forms.useApplicationIds.join(','),
            applicationExtends: applicationExtends
          }
          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"
        >
          {/*<NText style={'color:red'}>*/}
          {/*  注：应用无曲目声部时，适用应用不可选择*/}
          {/*</NText>*/}
          <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]
                }

                nextTick(() => tabsRef.value?.syncBarPosition())
              }}
            >
              {state.userProjectList.map((item: any) => (
                <NCheckbox value={item.value}>{item.label}</NCheckbox>
                // <NCheckbox value={item.value} disabled={item.disabled}>{item.label}</NCheckbox>
              ))}
            </NCheckboxGroup>
          </NFormItem>
          {state.selectAppKey.length > 0 && (
            <NTabs
              ref={tabsRef}
              type="line"
              v-model:value={state.tabName}
              onUpdate:value={(val: any) => {
                state.tabName = val
              }}
            >
              {state.selectAppKey.map((item: any, index: number) => {
                return (
                  <NTabPane
                    tab={state.appKeyNameMap.get(item)}
                    name={item}
                    displayDirective={'show'}
                  >
                    {item === 'GYM' && (
                      <div>
                        <NFormItem
                          label="曲目分类"
                          path="useProjectParamConfig.GYM.musicSheetCategoryId"
                          rule={[
                            {
                              required: gymFileRequire.value,
                              message: '请选择曲目分类'
                            }
                          ]}
                        >
                          <NCascader
                            valueField="id"
                            labelField="name"
                            children-field="children"
                            placeholder="请选择分类"
                            v-model:value={forms.useProjectParamConfig.GYM.musicSheetCategoryId}
                            options={state.musicSheetCategoryOptions.GYM}
                            onChange={() => {}}
                            clearable
                          />
                        </NFormItem>
                        <NFormItem
                          label="是否收费"
                          path="useProjectParamConfig.GYM.paymentType"
                          rule={[
                            {
                              required: gymFileRequire.value,
                              message: '请选择收费类型'
                            }
                          ]}
                        >
                          <NSelect
                            placeholder="请选择收费类型"
                            clearable
                            v-model:value={forms.useProjectParamConfig.GYM.paymentType}
                            options={getSelectDataFromObj(musicSheetPaymentType)}
                          ></NSelect>
                        </NFormItem>
                        <NFormItem label="排序值" path="useProjectParamConfig.GYM.sortNo">
                          <NInputNumber
                            v-model:value={forms.useProjectParamConfig.GYM.sortNo}
                            placeholder="请输入排序值"
                            clearable
                            min={0}
                            max={9999}
                            style={{ width: '100%' }}
                          />
                        </NFormItem>
                      </div>
                    )}
                    {item === 'GYT' && (
                      <div>
                        <NFormItem
                          label="分类"
                          path="useProjectParamConfig.GYT.musicSheetCategoryId"
                          rule={[
                            {
                              required: gytFileRequire.value,
                              message: '请选择分类'
                            }
                          ]}
                        >
                          <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.GYT.sortNo}
                            placeholder="请输入排序值"
                            clearable
                            min={0}
                            max={9999}
                            style={{ width: '100%' }}
                          />
                        </NFormItem>
                      </div>
                    )}
                    {item === 'KLX' && (
                      <div>
                        <NFormItem
                          label="可用途径"
                          path="useProjectParamConfig.KLX.availableType"
                          rule={[
                            {
                              required: klxFileRequire.value,
                              message: '请选择可用途径'
                            }
                          ]}
                        >
                          <NSelect
                            placeholder="请选择可用途径"
                            clearable
                            v-model:value={forms.useProjectParamConfig.KLX.availableType}
                            options={getSelectDataFromObj(musicSheetAvailableType)}
                          ></NSelect>
                        </NFormItem>
                        <NFormItem
                          label="曲目标签"
                          path="useProjectParamConfig.KLX.musicSheetCategoryId"
                          rule={[
                            {
                              required: klxFileRequire.value,
                              message: '请选择曲目标签'
                            }
                          ]}
                        >
                          <NSelect
                            placeholder="请选择曲目标签"
                            clearable
                            v-model:value={forms.useProjectParamConfig.KLX.musicSheetCategoryId}
                            options={[]}
                          ></NSelect>
                        </NFormItem>
                        <NFormItem
                          label="是否收费"
                          path="useProjectParamConfig.KLX.paymentType"
                          rule={[
                            {
                              required: klxFileRequire.value,
                              message: '请选择是否收费'
                            }
                          ]}
                        >
                          <NSelect
                            placeholder="请选择是否收费"
                            clearable
                            v-model:value={forms.useProjectParamConfig.KLX.paymentType}
                            options={[
                              {
                                label: '是',
                                value: 1
                              },
                              {
                                label: '否',
                                value: 0
                              }
                            ]}
                          ></NSelect>
                        </NFormItem>
                        <NFormItem
                          label="曲目价格"
                          path="useProjectParamConfig.KLX.musicPrice"
                          rule={[
                            {
                              required: klxFileRequire.value,
                              message: '请输入曲目价格'
                            }
                          ]}
                        >
                          <NInputNumber
                            style={'width:100%'}
                            placeholder="请输入曲目价格"
                            v-model:value={forms.useProjectParamConfig.KLX.musicPrice}
                          />
                        </NFormItem>
                        <NFormItem
                          label="是否置顶"
                          path="useProjectParamConfig.KLX.topFlag"
                          rule={[
                            {
                              required: klxFileRequire.value,
                              message: '请选择是否置顶'
                            }
                          ]}
                        >
                          <NSelect
                            placeholder="请选择是否置顶"
                            clearable
                            v-model:value={forms.useProjectParamConfig.KLX.topFlag}
                            options={[
                              {
                                label: '是',
                                value: 1
                              },
                              {
                                label: '否',
                                value: 0
                              }
                            ]}
                          ></NSelect>
                        </NFormItem>
                        <NFormItem
                          label="精品乐谱"
                          path="useProjectParamConfig.KLX.exquisiteFlag"
                          rule={[
                            {
                              required: klxFileRequire.value,
                              message: '请选择是否精品乐谱'
                            }
                          ]}
                        >
                          <NSelect
                            placeholder="请选择是否精品乐谱"
                            clearable
                            v-model:value={forms.useProjectParamConfig.KLX.exquisiteFlag}
                            options={[
                              {
                                label: '是',
                                value: 1
                              },
                              {
                                label: '否',
                                value: 0
                              }
                            ]}
                          ></NSelect>
                        </NFormItem>
                        <NFormItem label="排序值" path="useProjectParamConfig.KLX.sortNo">
                          <NInputNumber
                            v-model:value={forms.useProjectParamConfig.KLX.sortNo}
                            placeholder="请输入排序值"
                            clearable
                            min={0}
                            max={9999}
                            style={{ width: '100%' }}
                          />
                        </NFormItem>
                      </div>
                    )}
                    {item === 'KT' && (
                      <div>
                        <NFormItem
                          label="乐谱教材"
                          path="useProjectParamConfig.KT.musicSheetCategoryId"
                          rule={[
                            {
                              required: ktFileRequire.value,
                              message: '请选择乐谱教材'
                            }
                          ]}
                        >
                          <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}
                            max={9999}
                            style={{ width: '100%' }}
                          />
                        </NFormItem>
                      </div>
                    )}
                  </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>
    )
  }
})