import { AddOutline, TrashOutline } from '@vicons/ionicons5'
import {
  NForm,
  NFormItem,
  NInput,
  NSpace,
  NButton,
  NGrid,
  NGi,
  NInputGroup,
  NIcon,
  useDialog,
  useMessage
} from 'naive-ui'
import { defineComponent, PropType, reactive, ref } from 'vue'
import styles from './index.module.less'
import { orchestraSubsidyStandardSave, orchestraSubsidyStandardUpdate } from '../api'

export default defineComponent({
  name: 'city-operation',
  props: {
    type: {
      type: String,
      default: 'add'
    },
    data: {
      type: Object as PropType<any>,
      default: () => {
        return {}
      }
    }
  },
  emits: ['close', 'getList'],
  setup(props, { slots, attrs, emit }) {
    const baseConfig = {
      minStudentNum: null as any,
      maxStudentNum: null,
      singleSubsidy: null,
      ensembleSubsidy: null,
      musicTheorySubsidy: null,
      manageSubsidy: null
    }

    const btnLoading = ref(false)
    const forms = reactive({
      subsidyStandardName: '',
      config: [{ ...baseConfig }]
    })
    const formsRef = ref()
    const dialog = useDialog()
    const message = useMessage()

    // 初始化数据
    if (props.type === 'edit') {
      forms.subsidyStandardName = props.data.subsidyStandardName
      forms.config = JSON.parse(props.data.configJson)
    }

    // 只能输入数字
    const onlyAllowNumber = (value: string) => !value || /^\d+$/.test(value)

    //
    const minValidator = (rule: any, value: string) => {
      const t = rule.field.split(']')
      const index = t[0].split('[')[1]
      const prevMinStudentNum = forms.config[index - 1]?.maxStudentNum
      const maxStudentNum = forms.config[index]?.maxStudentNum
      return new Promise<void>((resolve, reject) => {
        if (!value) {
          reject(Error('请输入最小值'))
        } else if (
          ((Number(prevMinStudentNum) || 0) >= Number(value) ||
            (Number(value) > Number(maxStudentNum) && maxStudentNum)) &&
          index != '0'
        ) {
          reject(Error('数值输入有误'))
        } else if (value == '0') {
          reject(Error('数值必须大于0'))
        } else {
          resolve()
        }
      })
    }

    //
    const maxValidator = (rule: any, value: any) => {
      const t = rule.field.split(']')
      const index = t[0].split('[')[1]
      // const prevMinStudentNum = forms.config[index - 1]?.maxStudentNum
      const minStudentNum = forms.config[index]?.minStudentNum
      return new Promise<void>((resolve, reject) => {
        if (!value) {
          reject(Error('请输入最大值'))
        } else if ((Number(minStudentNum) || 0) > Number(value)) {
          reject(Error('数值输入有误'))
        } else if (value == '0') {
          reject(Error('数值必须大于0'))
        } else {
          resolve()
        }
      })
    }

    // 删除
    const onRemoveItem = (index: number) => {
      dialog.warning({
        title: '提示',
        content: '是否确定删除？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
          forms.config.splice(index, 1)
        }
      })
    }

    const onSubmit = async () => {
      formsRef.value?.validate(async (error: any) => {
        // console.log(error)
        if (error) return

        let checkNumber = true
        forms.config.forEach((config: any, index: number) => {
          // 从第二条数据开始判断
          const currentMaxNumber = Number(config.maxStudentNum)
          const nextConfig = forms.config[index + 1]
          console.log(nextConfig)
          // 判断是否有下一个
          if (nextConfig) {
            const nextMinNumber = Number(nextConfig.minStudentNum)
            console.log(currentMaxNumber, nextMinNumber)
            checkNumber = currentMaxNumber + 1 === nextMinNumber
          }
        })
        if (!checkNumber) {
          message.error('阶梯配置有误')
          return
        }

        try {
          btnLoading.value = true
          if (props.type === 'add') {
            await orchestraSubsidyStandardSave({
              subsidyStandardName: forms.subsidyStandardName,
              configJson: JSON.stringify(forms.config)
            })
            message.success('添加成功')
          } else if (props.type === 'edit') {
            await orchestraSubsidyStandardUpdate({
              id: props.data.id,
              subsidyStandardName: forms.subsidyStandardName,
              configJson: JSON.stringify(forms.config)
            })
            message.success('修改成功')
          }
          btnLoading.value = false
          emit('close')
          emit('getList')
        } catch {
          //
        }
      })
    }
    return () => (
      <div style="background: #fff; padding-top: 12px">
        <NForm
          model={forms}
          ref={formsRef}
          label-placement="top"
          label-width="auto"
          // requireMarkPlacement="left"
        >
          <NGrid cols={3} xGap={12}>
            <NGi>
              <NFormItem
                label="补助标准名称"
                path="subsidyStandardName"
                rule={[
                  {
                    required: true,
                    message: '请输入补助标准名称',
                    trigger: ['input', 'blur']
                  }
                ]}
              >
                <NInput
                  v-model:value={forms.subsidyStandardName}
                  placeholder="请输入补助标准名称"
                ></NInput>
              </NFormItem>
            </NGi>
          </NGrid>

          {forms.config &&
            forms.config.map((item: any, index: number) => (
              <div class={styles.section}>
                <NGrid cols={1}>
                  <NGi>
                    <NSpace justify="space-between" style="width: 100%; padding-bottom: 8px;">
                      <div style={{ fontSize: '16px', fontWeight: 'bold' }}>阶梯{index + 1}</div>
                      <NButton
                        quaternary
                        circle
                        disabled={index === 0 ? true : false}
                        onClick={() => onRemoveItem(index)}
                      >
                        {{
                          icon: () => (
                            <NIcon size={20}>
                              <TrashOutline />
                            </NIcon>
                          )
                        }}
                      </NButton>
                    </NSpace>
                  </NGi>
                </NGrid>
                <NGrid cols={3} xGap={12}>
                  <NGi>
                    <NInputGroup>
                      <NFormItem
                        label="学生人数范围"
                        path={`config[${index}].minStudentNum`}
                        rule={[
                          {
                            required: true,
                            trigger: ['input', 'blur'],
                            validator: minValidator
                          }
                        ]}
                      >
                        <NInput
                          v-model:value={item.minStudentNum}
                          clearable
                          placeholder="最小值"
                          disabled={index > 0 ? true : false}
                          allowInput={onlyAllowNumber}
                        >
                          {{ suffix: () => '人' }}
                        </NInput>
                      </NFormItem>
                      <span style="padding: 0 8px;display: flex;align-items: center;">至</span>
                      <NFormItem
                        path={`config[${index}].maxStudentNum`}
                        rule={[
                          {
                            required: true,
                            trigger: ['input', 'blur'],
                            validator: maxValidator
                          }
                        ]}
                      >
                        <NInput
                          v-model:value={item.maxStudentNum}
                          clearable
                          placeholder="最大值"
                          allowInput={onlyAllowNumber}
                          onUpdateValue={(val: any) => {
                            const config = forms.config[index + 1]
                            if (config) {
                              config.minStudentNum = val ? (Number(val) + 1).toString() : null
                            }
                          }}
                        >
                          {{ suffix: () => '人' }}
                        </NInput>
                      </NFormItem>
                    </NInputGroup>
                  </NGi>
                  <NGi>
                    <NFormItem
                      label="单技训练补助"
                      path={`config[${index}].singleSubsidy`}
                      rule={[
                        {
                          required: true,
                          message: '请输入单技训练补助',
                          trigger: ['input', 'blur']
                        }
                      ]}
                    >
                      <NInput
                        v-model:value={item.singleSubsidy}
                        clearable
                        placeholder="请输入单技训练补助"
                        allowInput={onlyAllowNumber}
                      >
                        {{ suffix: () => '元/次' }}
                      </NInput>
                    </NFormItem>
                  </NGi>
                  <NGi>
                    <NFormItem
                      label="合奏训练补助"
                      path={`config[${index}].ensembleSubsidy`}
                      rule={[
                        {
                          required: true,
                          message: '请输入合奏训练补助',
                          trigger: ['input', 'blur']
                        }
                      ]}
                    >
                      <NInput
                        v-model:value={item.ensembleSubsidy}
                        clearable
                        placeholder="请输入合奏训练补助"
                        allowInput={onlyAllowNumber}
                      >
                        {{ suffix: () => '元/次' }}
                      </NInput>
                    </NFormItem>
                  </NGi>

                  <NGi>
                    <NFormItem
                      label="乐理训练补助"
                      path={`config[${index}].musicTheorySubsidy`}
                      rule={[
                        {
                          required: true,
                          message: '请输入乐理训练补助',
                          trigger: ['input', 'blur']
                        }
                      ]}
                    >
                      <NInput
                        v-model:value={item.musicTheorySubsidy}
                        clearable
                        placeholder="请输入乐理训练补助"
                        allowInput={onlyAllowNumber}
                      >
                        {{ suffix: () => '元/次' }}
                      </NInput>
                    </NFormItem>
                  </NGi>
                  <NGi>
                    <NFormItem
                      label="管理补助"
                      path={`config[${index}].manageSubsidy`}
                      rule={[
                        {
                          required: true,
                          message: '请输入管理补助',
                          trigger: ['input', 'blur']
                        }
                      ]}
                    >
                      <NInput
                        v-model:value={item.manageSubsidy}
                        clearable
                        placeholder="请输入管理补助"
                        allowInput={onlyAllowNumber}
                      >
                        {{ suffix: () => '元/次' }}
                      </NInput>
                    </NFormItem>
                  </NGi>
                  <NGi>
                    <NFormItem
                      label="练习奖励"
                      path={`config[${index}].trainingSubsidy`}
                      rule={[
                        {
                          required: true,
                          message: '请输入练习奖励',
                          trigger: ['input', 'blur']
                        }
                      ]}
                    >
                      <NInput
                        v-model:value={item.trainingSubsidy}
                        clearable
                        placeholder="请输入练习奖励"
                        allowInput={onlyAllowNumber}
                      >
                        {{ suffix: () => '元/人' }}
                      </NInput>
                    </NFormItem>
                  </NGi>
                </NGrid>
              </div>
            ))}

          <div style={{ margin: '12px 0' }}>
            <NButton
              block
              type="default"
              onClick={() => {
                let minNumber = null as any
                if (forms.config.length > 0) {
                  minNumber = forms.config[forms.config.length - 1].maxStudentNum
                }
                forms.config.push({
                  ...baseConfig,
                  minStudentNum: minNumber ? (Number(minNumber) + 1).toString() : null
                })
              }}
            >
              {{ default: () => '添加标准', icon: () => <AddOutline /> }}
            </NButton>
          </div>
        </NForm>

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