import deepClone from '@/utils/deep.clone'
import { NForm, NInput, NSpace, NButton, useMessage, NGrid, NFormItemGi, NSelect } from 'naive-ui'
import { defineComponent, nextTick, onMounted, PropType, reactive, ref, shallowReactive } from 'vue'
import {
  productDetail,
  productList,
  subjectBasicConfigSave,
  subjectBasicConfigUpdate,
  subjectPage
} from '../api'
export default defineComponent({
  name: 'role-operation',
  props: {
    type: {
      type: String,
      default: 'add'
    },
    applyList: {
      type: Array as PropType<any>,
      default: () => []
    },
    data: {
      type: Object as PropType<any>,
      default: () => {}
    }
  },
  emits: ['close', 'getList'],
  setup(props, { slots, attrs, emit }) {
    const forms = reactive({
      subjectId: null,
      studentEnrollmentUpperLimit: null,
      instrumentsId: null,
      instrumentsSkuId: null,
      instrumentsOriginalPrice: null,
      instrumentsGroupPrice: null,
      textbookId: null,
      textbookSkuId: null,
      textbookOriginalPrice: null,
      textbookGroupPrice: null
    })
    const btnLoading = ref(false)
    const formsRef = ref()
    const message = useMessage()
    const state = shallowReactive({
      selectSubject: [],
      selectProduct: [],
      selectSkuProduct: [],
      selectSkuTextbook: []
    })

    const onSubmit = async () => {
      formsRef.value.validate(async (error: any) => {
        if (error) return false
        try {
          btnLoading.value = true

          if (props.type === 'add') {
            await subjectBasicConfigSave({ ...forms })
            message.success('添加成功')
          } else if (props.type === 'edit') {
            await subjectBasicConfigUpdate({
              ...forms,
              id: props.data.id
            })
            message.success('修改成功')
          }

          emit('close')
          emit('getList')
        } 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 getSubjectList = async () => {
      try {
        const { data } = await subjectPage({ page: 1, row: 999 })
        state.selectSubject = data.rows || []
      } catch {}
    }

    const getProductList = async () => {
      try {
        const { data } = await productList({ pageNum: 1, pageSize: 999 })
        const tempList = data.list || []
        tempList.forEach((item: any) => {
          item.label = item.name
          item.value = Number(item.id)
        })
        state.selectProduct = tempList
      } catch {}
    }

    const getProductDetail = async (id: string | number, type = 'instrument') => {
      try {
        const { data } = await productDetail({ id })
        if (type == 'instrument') {
          state.selectSkuProduct = skuStockList(data)
        } else {
          state.selectSkuTextbook = skuStockList(data)
        }
      } catch {}
    }

    const skuStockList = (data: any) => {
      // 处理规格
      const skuStockList = data.skuStockList || []
      skuStockList.forEach((item: any) => {
        if (item.spData) {
          const spData = JSON.parse(item.spData)
          item.label = spData.reduce((spDataJson: any, value: any) => {
            spDataJson += value.value
            return spDataJson
          }, '')
        } else {
          item.label = '默认'
        }
        item.value = Number(item.id)
      })
      return skuStockList
    }

    onMounted(async () => {
      getSubjectList()
      getProductList()
      if (props.type === 'edit') {
        const data = props.data
        getProductDetail(data.instrumentsId)
        getProductDetail(data.textbookId, 'textbook')
        forms.subjectId = data.subjectId
        forms.studentEnrollmentUpperLimit = data.studentEnrollmentUpperLimit
        forms.instrumentsId = data.instrumentsId
        forms.instrumentsSkuId = data.instrumentsSkuId
        forms.instrumentsOriginalPrice = data.instrumentsOriginalPrice
        forms.instrumentsGroupPrice = data.instrumentsGroupPrice
        forms.textbookId = data.textbookId
        forms.textbookSkuId = data.textbookSkuId
        forms.textbookOriginalPrice = data.textbookOriginalPrice
        forms.textbookGroupPrice = data.textbookGroupPrice
      }
    })

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

    return () => (
      <div style="background: #fff; padding-top: 12px">
        <NForm model={forms} ref={formsRef} label-placement="left" label-width="auto">
          <NGrid cols={2} xGap="12">
            <NFormItemGi
              label="声部"
              path="subjectId"
              rule={[
                {
                  required: true,
                  message: '请选择声部'
                }
              ]}
            >
              <NSelect
                v-model:value={forms.subjectId}
                options={state.selectSubject}
                valueField="id"
                labelField="name"
                placeholder="请选择声部"
                clearable
              />
            </NFormItemGi>
            <NFormItemGi
              label="招生人数限制"
              path="studentEnrollmentUpperLimit"
              // rule={[
              //   {
              //     required: true,
              //     message: '请输入招生人数限制'
              //   }
              // ]}
            >
              <NInput
                v-model:value={forms.studentEnrollmentUpperLimit}
                allowInput={onlyAllowNumber}
                placeholder="请输入招生人数限制"
                clearable
                maxlength={8}
              ></NInput>
            </NFormItemGi>
            <NFormItemGi
              label="开团乐器"
              path="instrumentsId"
              rule={[
                {
                  required: true,
                  message: '请选择开团乐器'
                }
              ]}
            >
              <NSelect
                v-model:value={forms.instrumentsId}
                options={state.selectProduct}
                placeholder="请选择开团乐器"
                filterable
                onUpdate:value={(value: any, options: any) => {
                  forms.instrumentsSkuId = null
                  forms.instrumentsGroupPrice = null
                  // forms.instrumentsOriginalPrice = null
                  // console.log(value, options)
                  forms.instrumentsOriginalPrice = options.originalPrice || 0
                  getProductDetail(value)
                }}
                clearable
              />
            </NFormItemGi>
            <NFormItemGi
              label="乐器规格"
              path="instrumentsSkuId"
              rule={[
                {
                  required: true,
                  message: '请选择乐器规格'
                }
              ]}
            >
              <NSelect
                v-model:value={forms.instrumentsSkuId}
                options={state.selectSkuProduct}
                placeholder="请选择乐器规格"
                onUpdate:value={(value: any, options: any) => {
                  // console.log(value, options)
                  // forms.instrumentsOriginalPrice = options.originalPrice || 0
                }}
                clearable
              />
            </NFormItemGi>
            <NFormItemGi
              label="乐器原价"
              path="instrumentsOriginalPrice"
              rule={[
                {
                  required: true,
                  message: '请输入乐器原价'
                }
              ]}
            >
              <NInput
                v-model:value={forms.instrumentsOriginalPrice}
                disabled
                placeholder="请输入乐器原价"
                clearable
                maxlength={8}
              ></NInput>
            </NFormItemGi>
            <NFormItemGi
              label="乐器开团价"
              path="instrumentsGroupPrice"
              rule={[
                {
                  required: true,
                  message: '请选择输入开团价'
                },
                {
                  pattern: /^(?:0.\d{0,3}|[0-9][0-9]{0,12}|[0-9]{1,10}.\d{0,3})$/,
                  message: '输入乐器开团价有误',
                  trigger: ['blur']
                }
              ]}
            >
              <NInput
                v-model:value={forms.instrumentsGroupPrice}
                placeholder="请输入乐器开团价"
                clearable
                maxlength={8}
              ></NInput>
            </NFormItemGi>
            <NFormItemGi
              label="教材"
              path="textbookId"
              rule={[
                {
                  required: true,
                  message: '请选择教材'
                }
              ]}
            >
              <NSelect
                v-model:value={forms.textbookId}
                options={state.selectProduct}
                placeholder="请选择教材"
                filterable
                onUpdate:value={(value: any, options: any) => {
                  forms.textbookSkuId = null
                  forms.textbookGroupPrice = null
                  // forms.textbookOriginalPrice = null
                  forms.textbookOriginalPrice = options.originalPrice || 0
                  getProductDetail(value, 'textbook')
                }}
                clearable
              />
            </NFormItemGi>
            <NFormItemGi
              label="教材规格"
              path="textbookSkuId"
              rule={[
                {
                  required: true,
                  message: '请选择教材规格'
                }
              ]}
            >
              <NSelect
                v-model:value={forms.textbookSkuId}
                options={state.selectSkuTextbook}
                placeholder="请选择教材规格"
                onUpdate:value={(value: any, options: any) => {
                  // console.log(value, options)
                  // forms.textbookOriginalPrice = options.originalPrice || 0
                }}
                clearable
              />
            </NFormItemGi>
            <NFormItemGi
              label="教材原价"
              path="textbookOriginalPrice"
              rule={[
                {
                  required: true,
                  message: '请输入教材原价'
                }
              ]}
            >
              <NInput
                v-model:value={forms.textbookOriginalPrice}
                disabled
                placeholder="请输入教材原价"
                clearable
                maxlength={8}
              ></NInput>
            </NFormItemGi>
            <NFormItemGi
              label="教材团购价"
              path="textbookGroupPrice"
              rule={[
                {
                  required: true,
                  message: '请输入教材团购价'
                },
                {
                  pattern: /^(?:0.\d{0,3}|[0-9][0-9]{0,12}|[0-9]{1,10}.\d{0,3})$/,
                  message: '输入乐器开团价有误',
                  trigger: ['blur', 'input']
                }
              ]}
            >
              <NInput
                v-model:value={forms.textbookGroupPrice}
                maxlength={8}
                placeholder="请输入教材团购价"
                clearable
              />
            </NFormItemGi>
          </NGrid>
        </NForm>

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