import { NForm, NFormItem, NInput, NSelect, NSpace, NButton, useMessage, NCascader } from 'naive-ui'
import type { TreeSelectOption } from 'naive-ui'
import { defineComponent, onMounted, PropType, reactive, ref } from 'vue'
import { cityFeeSettingSave, cityFeeSettingUpdate, orchestraSubsidyStandardPage } from '../api'

export default defineComponent({
  name: 'city-operation',
  props: {
    type: {
      type: String,
      default: 'add'
    },
    data: {
      type: Object as PropType<any>,
      default: () => {}
    },
    areaList: {
      type: Array as PropType<Array<TreeSelectOption>>,
      default: () => []
    }
  },
  emits: ['close', 'getList'],
  setup(props, { slots, attrs, emit }) {
    const forms = reactive({
      cityCode: null,
      provinceCode: null, // 省号
      vipPrice: null,
      vipGroupPrice: null,
      vipOriginalPrice: null,
      orchestraSubsidyStandardId: null,
      vipDurationMonth: 6 // 固定半年
    })

    const btnLoading = ref(false)
    const formsRef = ref()
    const subsidyList = ref<any>([])
    const message = useMessage()

    // 获取补助标准列表
    const getSubsidy = async () => {
      try {
        const res = await orchestraSubsidyStandardPage({
          page: 1,
          rows: 100
        })
        const data = res.data.rows || []
        const tempList = [] as any
        data.forEach((item: any) => {
          tempList.push({ label: item.subsidyStandardName, value: item.id })
        })
        subsidyList.value = tempList
      } catch {
        //
      }
    }

    // 提交记录
    const onSubmit = async () => {
      formsRef.value.validate(async (error: any) => {
        if (error) return
        try {
          console.log(forms, 'forms')
          const ids = formatParentAreaId(forms.cityCode, props.areaList)
          forms.provinceCode = ids[0]
          btnLoading.value = true
          if (props.type === 'add') {
            await cityFeeSettingSave({ ...forms })
            message.success('添加成功')
          } else if (props.type === 'edit') {
            await cityFeeSettingUpdate({ ...forms, id: props.data.id })
            message.success('修改成功')
          }
          emit('getList')
          emit('close')
          setTimeout(() => {
            btnLoading.value = false
          }, 100)
        } catch {
          //
          btnLoading.value = false
        }
      })
    }
    // const formatParentId = (id: any, list: any, ids = [] as any) => {
    //   for (const item of list) {
    //     if (item.children && item.children.length > 0) {
    //       const cIds: any = formatParentId(id, item.children, [...ids, item.code])
    //       if (cIds.includes(id)) {
    //         return cIds
    //       }
    //     }
    //     if (item.code === id) {
    //       return [...ids, id]
    //     }
    //   }
    //   return ids
    // }

    const formatParentAreaId = (id: any, list: any, ids = [] as any) => {
      for (const item of list) {
        if (item.areas && item.areas.length > 0) {
          const cIds: any = formatParentAreaId(id, item.areas, [...ids, item.code])
          if (cIds.includes(id)) {
            return cIds
          }
        }
        if (item.code === id) {
          return [...ids, id]
        }
      }
      return ids
    }

    onMounted(async () => {
      getSubsidy()

      // 初始化数据
      if (props.type === 'edit') {
        console.log(props.data, 'data')
        forms.cityCode = props.data.cityCode
        forms.provinceCode = props.data.provinceCode
        forms.vipPrice = props.data.vipPrice.toString()
        forms.vipGroupPrice = props.data.vipGroupPrice.toString()
        forms.vipOriginalPrice = props.data.vipOriginalPrice.toString()
        forms.orchestraSubsidyStandardId = props.data.orchestraSubsidyStandardId
      }
    })

    // 只能输入数字
    const onlyAllowNumber = (value: string) =>
      !value || /^(?:0.\d{0,3}|[0-9][0-9]{0,12}|[0-9]{1,10}.\d{0,3})$/.test(value)
    return () => (
      <div style="background: #fff; padding-top: 12px">
        <NForm model={forms} ref={formsRef} label-placement="left" label-width="auto">
          <NFormItem
            label="城市"
            path="cityCode"
            rule={[
              {
                required: true,
                message: '请输入城市'
              }
            ]}
          >
            <NCascader
              placeholder="请选择城市"
              v-model:value={forms.cityCode}
              options={props.areaList}
              checkStrategy="child"
              childrenField="areas"
              valueField="code"
              labelField="name"
              expandTrigger="hover"
              clearable
            />
          </NFormItem>
          <NFormItem
            label="团练宝零售价"
            path="vipPrice"
            rule={[
              {
                required: true,
                message: '请输入团练宝零售价'
              }
            ]}
          >
            <NInput
              v-model:value={forms.vipPrice}
              placeholder="请输入团练宝零售价"
              allowInput={onlyAllowNumber}
              clearable
            >
              {{ suffix: () => '元/6个月' }}
            </NInput>
          </NFormItem>
          <NFormItem
            label="团练宝团购价"
            path="vipGroupPrice"
            rule={[
              {
                required: true,
                message: '请输入团练宝团购价'
              }
            ]}
          >
            <NInput
              v-model:value={forms.vipGroupPrice}
              placeholder="请输入团练宝团购价"
              allowInput={onlyAllowNumber}
              clearable
            >
              {{ suffix: () => '元/6个月' }}
            </NInput>
          </NFormItem>
          <NFormItem
            label="团练宝原价"
            path="vipOriginalPrice"
            rule={[
              {
                required: true,
                message: '请输入团练宝原价'
              }
            ]}
          >
            <NInput
              v-model:value={forms.vipOriginalPrice}
              placeholder="请输入团练宝原价"
              allowInput={onlyAllowNumber}
              clearable
            >
              {{ suffix: () => '元/6个月' }}
            </NInput>
          </NFormItem>
          {/* <NFormItem
            label="补助标准"
            path="orchestraSubsidyStandardId"
            rule={[
              {
                required: true,
                message: '请选择补助标准'
              }
            ]}
          >
            <NSelect
              v-model:value={forms.orchestraSubsidyStandardId}
              options={subsidyList.value}
              placeholder="请选择补助标准"
              clearable
            ></NSelect>
          </NFormItem> */}
        </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>
    )
  }
})
