<template>
  <view class="p-base">
    <CuNavbar :title="title"></CuNavbar>
    <view class="card-shadow px-base">
      <uv-form
        labelPosition="left"
        :model="form"
        :rules="rules"
        ref="formRef"
        errorType="toast"
        labelWidth="150rpx"
      >
        <template v-if="type == 'store' && checkPermission(['admin'])">
          <uv-form-item label="门店" prop="" @click="showStoreSelect">
            <uv-input
              disabled
              disabledColor="#ffffff"
              placeholder="请选择门店"
              inputAlign="right"
              :border="`none`"
              v-model="form.store"
            >
            </uv-input>
            <template v-slot:right>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
        </template>
        <template v-if="type == 'info'">
          <uv-line color="#f5f5f5"></uv-line>
          <uv-form-item required label="姓名" prop="name">
            <uv-input
              placeholder="请输入姓名"
              inputAlign="right"
              :border="`none`"
              v-model="form.name"
            >
            </uv-input>
          </uv-form-item>
          <uv-line color="#f5f5f5"></uv-line>
          <uv-form-item required label="手机号" prop="phone">
            <uv-input
              placeholder="请输入手机号"
              inputAlign="right"
              :border="`none`"
              type="number"
              maxlength="11"
              v-model="form.phone"
            >
            </uv-input>
          </uv-form-item>
          <uv-line color="#f5f5f5"></uv-line>
          <template v-if="!isEdit">
            <uv-form-item required label="登录用户名" prop="username">
              <uv-input
                placeholder="请输入登录用户名"
                inputAlign="right"
                v-model="form.username"
                :border="`none`"
              >
              </uv-input>
            </uv-form-item>
            <uv-line color="#f5f5f5"></uv-line>
          </template>
          <uv-form-item :required="!isEdit" label="登录密码" prop="password">
            <uv-input
              placeholder="请输入登录密码"
              inputAlign="right"
              maxlength="15"
              type="password"
              v-model="form.password"
              :border="`none`"
            >
            </uv-input>
          </uv-form-item>
        </template>
      </uv-form>
    </view>
    <view class="mt-100rpx">
      <uv-button type="primary" @click="submit">保存</uv-button>
    </view>

    <uv-modal
      ref="modalRef"
      title="提示"
      content="确定提交员工信息？"
      @confirm="onSubmit"
      :showCancelButton="true"
    ></uv-modal>

    <StorePopup
      :id="form.store_id"
      ref="storeRef"
      @change="storeChange"
    ></StorePopup>
  </view>
</template>
<script setup>
import CuNavbar from '@/components/cu-navbar/index'
import { ref, reactive, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { mobile } from '@climblee/uv-ui/libs/function/test'
import { http } from '@/utils/request'
import StorePopup from '@/pages/user/components/store-popup.vue'
import checkPermission from '@/utils/permission'
const storeRef = ref(null)
const formRef = ref(null)
const modalRef = ref(null)
const id = ref(0)
const loading = ref(false)
const type = ref('info')
const form = reactive({
  name: '',
  phone: '',
  username: '',
  password: '',
  confirm_password: '',
  store_id: '',
  store: '',
})
const rules = computed(() => {
  return {
    name: [{ required: true, message: '请输入姓名' }],
    phone: [
      { required: true, message: '请输入手机号' },
      {
        max: 11,
        message: '请输入正确的手机号',
      },
    ],
    username: [{ required: true, message: '请输入登录用户名' }],
    password: [
      { required: !isEdit.value, message: '请输入登录密码' },
      {
        min: 6,
        message: '密码不能少于6位字符',
      },
      {
        validator: (rule, value) => {
          return /^[^\u4e00-\u9fa5]{0,}$/.test(value)
        },
        message: '密码不能包含中文',
      }
    ],
    confirm_password: [
      { required: !isEdit.value, message: '请输入登录密码' },
      {
        validator: (rule, value) => {
          return form.password === value
        },
        message: '两次密码不一致',
      },
    ],
  }
})
onLoad((options) => {
  id.value = options.id
  type.value = options.type || 'info'
  if (isEdit.value) getDetail()
})
const isEdit = computed(() => !!id.value)
const title = computed(() => (isEdit.value ? '员工修改' : '员工添加'))

const storeChange = (data) => {
  form.store_id = data.id
  form.store = data.title
  storeRef.value.close()
}

const submit = () => {
  formRef.value.validate().then((res) => {
    modalRef.value.open()
  })
}

const showStoreSelect = () => {
  // uni.$emit('showStoreSelect')
  storeRef.value.open()
}

const onSubmit = () => {
  if (isEdit.value) {
    updateUser()
  } else {
    addUser()
  }
}
const updateUser = async () => {
  if (loading.value) {
    return
  }
  loading.value = true
  try {
    await http.put(`/hr/employee/${id.value}`, {
      ...form,
    })
    uni.showToast({
      title: '修改成功',
      icon: 'none',
    })
    uni.$emit('user:onRefresh')
    setTimeout(() => {
      uni.navigateBack()
      formRef.value.resetFields()
    }, 2000)
  } catch (error) {
  } finally {
    loading.value = false
  }
}
const addUser = async () => {
  if (loading.value) {
    return
  }
  loading.value = true
  try {
    await http.post('/hr/employee', {
      ...form,
    })
    formRef.value.resetFields()
    uni.showToast({
      title: '添加成功',
      duration: 2000,
      icon: 'none',
    })
    uni.$emit('user:onRefresh')
  } catch (error) {
  } finally {
    loading.value = false
  }
}

const getDetail = () => {
  http.get(`/hr/employee/${id.value}`).then((res) => {
    const info = {
      name: res.name,
      phone: res.phone,
      username: res.username,
    }
    Object.assign(form, info, { store: res.store?.title })
  })
}
</script>
