import deepClone from '@/utils/deep.clone'
import { queryAllProvince, sysAreaPage } from '@/views/city-manage/api'
import dayjs from 'dayjs'
import {
  NForm,
  NFormItem,
  NInput,
  NSpace,
  NButton,
  useMessage,
  NRadioGroup,
  NRadio,
  NCascader,
  NGrid,
  NFormItemGi,
  NSelect,
  NDatePicker,
  NAlert
} from 'naive-ui'
import {
  defineComponent,
  nextTick,
  onMounted,
  PropType,
  reactive,
  ref,
  shallowReactive,
  shallowRef
} from 'vue'
import {
  sysEmployeeDetail,
  sysEmployeeSave,
  sysEmployeeUpdate,
  sysPositionPage,
  sysRolePage
} 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({
      nickname: null,
      phone: null,
      gender: null,
      entryDate: null,
      roleList: [],
      positionList: [],
      employeeCityList: [],
      userReceiveAddress: {
        name: null,
        phoneNumber: null,
        address: null, //临时
        province: null,
        city: null,
        region: null,
        detailAddress: null
      } as any
    })
    const btnLoading = ref(false)
    const formsRef = ref()
    const message = useMessage()
    const state = shallowReactive({
      selectRole: [],
      selectPosition: [],
      selectCity: [] as any,
      selectCityEmployee: [] as any
    })

    const onSubmit = async () => {
      console.log(forms.userReceiveAddress.address, '1212', state.selectCity)
      const selectArea =
        formatParentAreaId(forms.userReceiveAddress.address, state.selectCity) || []
      // if (selectArea.length > 0) {
      console.log(selectArea, 'selectArea')
      forms.userReceiveAddress.province = selectArea[0] || null
      forms.userReceiveAddress.city = selectArea[1] || null
      forms.userReceiveAddress.region = selectArea[2] || selectArea[1] || null
      // }
      formsRef.value.validate(async (error: any) => {
        if (error) return false
        try {
          btnLoading.value = true
          const { roleList, positionList, entryDate, employeeCityList, ...res } = forms
          console.log(roleList, positionList, employeeCityList)

          const tempRoleList: any = []
          if (roleList && roleList.length > 0) {
            roleList.forEach((item: any) => {
              tempRoleList.push({
                roleName: ' ',
                id: item
              })
            })
          }
          const tempPositionList: any = []
          if (positionList) {
            tempPositionList.push({
              roleName: ' ',
              id: positionList
            })
          }

          const tempEmployeeList: any = []
          if (employeeCityList && employeeCityList.length > 0) {
            employeeCityList.forEach((item: any) => {
              const itemCode = formatParentAreaId(item, state.selectCity)
              tempEmployeeList.push({
                cityCode: itemCode[1],
                provinceCode: itemCode[0]
              })
            })
          }

          if (props.type === 'add') {
            await sysEmployeeSave({
              ...res,
              roleList: tempRoleList,
              positionList: tempPositionList,
              employeeCityList: tempEmployeeList,
              entryDate: dayjs(entryDate).format('YYYY-MM-DD HH:mm:ss')
            })
            message.success('添加成功')
          } else if (props.type === 'edit') {
            await sysEmployeeUpdate({
              ...res,
              roleList: tempRoleList,
              positionList: tempPositionList,
              employeeCityList: tempEmployeeList,
              entryDate: dayjs(entryDate).format('YYYY-MM-DD HH:mm:ss'),
              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 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
    }

    const getPositionList = async () => {
      try {
        const { data } = await sysPositionPage({ page: 1, rows: 999 })
        state.selectPosition = data.rows || []
      } catch {}
    }

    const getRoleList = async () => {
      try {
        const { data } = await sysRolePage({ page: 1, rows: 999, enable: true })
        state.selectRole = data.rows || []
      } catch {}
    }

    const phoneValidater = (rule: any, value: string) => {
      if (!value) {
        return true
      } else if (
        !/^((13[0-9])|(14(0|[5-7]|9))|(15([0-3]|[5-9]))|(16(2|[5-7]))|(17[0-8])|(18[0-9])|(19([0-3]|[5-9])))\d{8}$/.test(
          value
        )
      ) {
        return new Error('请输入正确的手机号')
      } else {
        return true
      }
    }

    const getAreaList = async (parentId = 0) => {
      try {
        const { data } = await queryAllProvince()
        const tempList = data || []
        state.selectCity = deepClone(tempList)
        state.selectCityEmployee = tempList.map((item: any) => {
          item.isLeaf = false
          item.areas.map((area: any) => {
            area.isLeaf = true
            area.areas = null
          })
          return item
        })
      } catch {
        //
      }
    }

    onMounted(async () => {
      getPositionList()
      getRoleList()
      getAreaList()
      if (props.type === 'edit') {
        const data = props.data
        try {
          const res = await sysEmployeeDetail({ id: data.id })
          const detail = res.data || {}
          forms.nickname = detail.nickname
          forms.phone = detail.phone
          forms.gender = detail.gender
          forms.entryDate = detail.entryDate && new Date(detail.entryDate).getTime()
          forms.roleList =
            detail.roleList &&
            detail.roleList.map((position: any) => {
              return position.id
            })
          forms.positionList =
            (detail.positionList && detail.positionList.length > 0 && detail.positionList[0].id) ||
            null
          forms.employeeCityList =
            detail.employeeCityList &&
            detail.employeeCityList.map((city: any) => {
              return Number(city.cityCode)
            })
          const userReceiveAddress = detail.userReceiveAddress || {}
          forms.userReceiveAddress = {
            id: userReceiveAddress.id,
            name: userReceiveAddress.name,
            phoneNumber: userReceiveAddress.phoneNumber,
            address: Number(userReceiveAddress.region || userReceiveAddress.city) || null, //临时
            province: userReceiveAddress.province,
            city: userReceiveAddress.city,
            region: userReceiveAddress.region,
            detailAddress: userReceiveAddress.detailAddress
          }
        } catch {}
      }
    })

    return () => (
      <div style="background: #fff; padding-top: 12px">
        <NForm model={forms} ref={formsRef} label-placement="left" label-width="auto">
          <NAlert title="基本信息" showIcon={false} bordered={false} style="margin-bottom: 12px;" />
          <NGrid cols={2}>
            <NFormItemGi
              label="员工姓名"
              path="nickname"
              rule={[
                {
                  required: true,
                  message: '请输入员工姓名'
                }
              ]}
            >
              <NInput
                v-model:value={forms.nickname}
                placeholder="请输入员工姓名"
                clearable
                maxlength={100}
              ></NInput>
            </NFormItemGi>
            <NFormItemGi
              label="手机号"
              path="phone"
              rule={[
                {
                  required: true,
                  message: '请输入手机号'
                },
                {
                  pattern:
                    /^((13[0-9])|(14(0|[5-7]|9))|(15([0-3]|[5-9]))|(16(2|[5-7]))|(17[0-8])|(18[0-9])|(19([0-3]|[5-9])))\d{8}$/,
                  message: '请输入正确的手机号',
                  trigger: 'blur'
                }
              ]}
            >
              <NInput
                v-model:value={forms.phone}
                placeholder="请输入手机号"
                clearable
                maxlength={11}
              ></NInput>
            </NFormItemGi>
            <NFormItemGi
              label="性别"
              path="gender"
              rule={[
                {
                  required: true,
                  message: '请选择性别'
                }
              ]}
            >
              <NRadioGroup v-model:value={forms.gender}>
                <NSpace>
                  <NRadio value={1}>男</NRadio>
                  <NRadio value={0}>女</NRadio>
                </NSpace>
              </NRadioGroup>
            </NFormItemGi>
            <NFormItemGi
              label="入职日期"
              path="entryDate"
              rule={[
                {
                  required: true,
                  message: '请选择入职日期'
                }
              ]}
            >
              <NDatePicker
                v-model:value={forms.entryDate}
                type="date"
                // valueFormat="yyyy-MM-dd mm:hh:ss"
                style="width: 100%"
              />
            </NFormItemGi>
            <NFormItemGi
              label="角色"
              path="roleList"
              rule={[
                {
                  required: true,
                  message: '请选择角色'
                }
              ]}
            >
              <NSelect
                v-model:value={forms.roleList}
                options={state.selectRole}
                labelField="roleName"
                valueField="id"
                placeholder="请选择角色"
                multiple
                maxTagCount={'responsive'}
                clearable
              />
            </NFormItemGi>
            <NFormItemGi
              label="岗位"
              path="positionList"
              rule={[
                {
                  required: true,
                  message: '请选择角色'
                }
              ]}
            >
              <NSelect
                v-model:value={forms.positionList}
                options={state.selectPosition}
                labelField="roleName"
                valueField="id"
                clearable
                placeholder="请选择岗位"
                maxTagCount={'responsive'}
              />
            </NFormItemGi>
            <NFormItemGi
              label="负责城市"
              path="employeeCityList"
              rule={[
                {
                  required: true,
                  message: '请选择负责城市'
                }
              ]}
            >
              <NCascader
                v-model:value={forms.employeeCityList}
                options={state.selectCityEmployee}
                labelField="name"
                valueField="code"
                childrenField="areas"
                checkStrategy="child"
                showPath={false}
                clearable
                multiple
                maxTagCount={'responsive'}
                placeholder="请选择负责城市"
              />
            </NFormItemGi>
          </NGrid>

          <NAlert title="维修地址" showIcon={false} bordered={false} style="margin-bottom: 12px;" />
          <NGrid cols={2}>
            <NFormItemGi label="员工姓名" path="userReceiveAddress.name">
              <NInput
                v-model:value={forms.userReceiveAddress.name}
                placeholder="请输入员工姓名"
                clearable
                maxlength={100}
              ></NInput>
            </NFormItemGi>
            <NFormItemGi
              label="手机号"
              path="userReceiveAddress.phoneNumber"
              rule={[
                {
                  validator: phoneValidater,
                  trigger: 'blur'
                }
              ]}
            >
              <NInput
                v-model:value={forms.userReceiveAddress.phoneNumber}
                placeholder="请输入手机号"
                clearable
                maxlength={11}
                style="width: 100%;"
              ></NInput>
            </NFormItemGi>
          </NGrid>
          <NFormItem label="省市区" path="userReceiveAddress.address">
            <NCascader
              v-model:value={forms.userReceiveAddress.address}
              options={state.selectCity}
              labelField="name"
              valueField="code"
              childrenField="areas"
              checkStrategy="child"
              showPath={true}
              clearable
              maxTagCount={'responsive'}
              placeholder="请选择省市区"
            />
          </NFormItem>
          <NFormItem label="详情地址" path="userReceiveAddress.detailAddress">
            <NInput
              v-model:value={forms.userReceiveAddress.detailAddress}
              maxlength={180}
              type="textarea"
              rows={2}
              placeholder="请输入详情地址"
              clearable
            />
          </NFormItem>
        </NForm>

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