<script setup>
import { apiSystemCommon } from '@/api/system'
import { apiCustomerUser } from '@/api/customer'
import { isMobileNo, patternEmail } from '@/utils/common'
import { useRoute, useRouter } from 'vue-router'
import PermissionTable from './components/PermissionTable.vue'
import { dayjs, ElMessageBox } from 'element-plus'
import OperationRecord from './components/OperationRecord.vue'

const route = useRoute()
const router = useRouter()

const userId = ref(route.query.id || 0)

const isView = computed(() => {
  return route.path === '/customer/userDetail'
})

const areaCodeOpts = ref([])
function getPhoneAreaCode() {
  apiSystemCommon.phoneAreaCode().then(res => {
    if (res.Ret === 200) {
      areaCodeOpts.value = res.Data || []
    }
  })
}
getPhoneAreaCode()




const formRef = ref(null)
const formRules = {
  realName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  phone: [{
    required: true,
    validator: (rule, value, callback) => {
      if (value === '' && !formState.email) {
        callback(new Error('手机号码和邮箱至少填一个'));
      } else if (value && formState.areaCode === '86' && !isMobileNo(value || '')) {
        callback(new Error('请输入正确的手机号格式'));
      } else if (formState.areaCode !== '86' && isNaN(value?.trim())) {
        callback(new Error('请输入正确的手机号格式'));
      } else {
        callback();
      }
    }, trigger: 'blur'
  }],
  email: [{
    validator: (rule, value, callback) => {
      if (value === '' && !formState.phone) {
        callback(new Error('手机号码和邮箱至少填一个'));
      } else if (value && !patternEmail.test(value)) {
        callback(new Error('请输入正确的邮箱格式'));
      } else {
        callback();
      }
    }, trigger: 'blur'
  }],
  validTime: [{ required: true, message: '请选择有效期', trigger: 'change' }],
  company: [{ required: true, message: '所属公司不能为空', trigger: 'blur' }],
  sellerId: [{ required: true, message: '请选择销售', trigger: 'change' }],
}
const showPhoneVal=computed({
  get(){
    return formState.phone
  },
  set(value){
    // formState.phone=value.replace(/\s+/g, ''); //`\s`在正则表达式中匹配的不仅仅是空格；它还匹配制表符、换行符等。如果只想替换普通的空白字符（即ASCII码中的32号字符）
    formState.phone=value.replace(/ /g, '');
  }
})
const formState = reactive({
  realName: '',
  areaCode: '86',
  phone: '',
  email: '',
  sellerId: '',
  validTime: '',
  company: '',
  isEnabled: false

})


const checkedIds = ref([])

function getUserInfo() {
  if (!userId.value) return
  apiCustomerUser.userInfo({
    UserId: userId.value
  }).then(res => {
    if (res.Ret === 200) {
      const { Detail } = res.Data
      formState.realName = Detail.RealName
      formState.areaCode = Detail.AreaCode
      formState.phone = Detail.Phone
      formState.email = Detail.Email
      formState.sellerId = Detail.SellerId||''
      formState.validTime = Detail.ValidStartTime?[dayjs(Detail.ValidStartTime).format('YYYY-MM-DD'), dayjs(Detail.ValidEndTime).format('YYYY-MM-DD')]:''
      formState.company = Detail.Company
      formState.isEnabled = Detail.Status ? true : false
      if(route.query.startTime){
        formState.validTime=[route.query.startTime,route.query.endTime]
      }
    }
  })
}
getUserInfo()


function handleToEdit() {
  // 关闭提示
  formState.isEnabled=true
  ElMessageBox.close()
  router.replace({
    path: '/customer/userEdit',
    query: {
      id: userId.value
    }
  })
}
function checkAddContent(msg) {
  return h('p', [
    msg,
    h(ElButton, {
      type: 'primary',
      link: true,
      onClick: handleToEdit
    }, '跳转查看')
  ]);
}



async function handleSave(type) {
  await formRef.value.validate()
  let params = {
    RealName: formState.realName,
    AreaCode: formState.areaCode,
    Phone: formState.phone,
    Email: formState.email,
    SellerId: formState.sellerId,
    ValidStartTime: formState.validTime?.[0],
    ValidEndTime: formState.validTime?.[1],
    Company: formState.company,
    ChartPermission: checkedIds.value
  }
  if (userId.value) {
    params.UserId = Number(userId.value)
    params.IsEnabled = formState.isEnabled
  } else {
    // 新增用户时进行校验
    const checkRes = await apiCustomerUser.userAddCheck({
      AreaCode: formState.areaCode,
      Phone: formState.phone,
      Email: formState.email,
    })
    if (checkRes.Ret !== 200) return
    if (checkRes.Data) {
      userId.value = checkRes.Data.UserId
      ElMessageBox.confirm(checkAddContent(checkRes.Msg),'操作提示',{
        autofocus:false,
      }).then(()=>{
        // 确认则自动调用编辑保存一次用户信息
        formState.isEnabled=true
        handleSave()
      }).catch(()=>{})
      return
    }
  }
  let res
  if(route.name==='CustomerUserTransform'){
    res=await apiCustomerUser.potentialUserEdit(params)
  }else{
    res = userId.value ? await apiCustomerUser.userEdit(params) : await apiCustomerUser.userAdd(params)
  }
  if (res.Ret !== 200) return
  ElMessage.success(userId.value ? '编辑成功' : '新增成功')
  router.replace('/customer/userList')

}

</script>

<template>
  <div class="bg-white flex customer-user-edit-page">
    <div class="content-box">
      <el-form
        ref="formRef"
        :model="formState"
        :rules="formRules"
        label-width="100px"
        :disabled="isView"
      >
        <div class="flex form-tr-box">
          <el-form-item label="姓名" prop="realName">
            <el-input v-model="formState.realName" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-select
              v-model="formState.areaCode"
              placeholder="请选择"
              style="width: 35%"
            >
              <el-option
                v-for="item in areaCodeOpts"
                :key="item.Value"
                :label="item.Name"
                :value="item.Value"
              />
            </el-select>
            <el-input
              v-model="showPhoneVal"
              placeholder="手机号和邮箱至少填一个"
              style="width: 60%; margin-left: 5%"
            />
          </el-form-item>
        </div>
        <div class="flex form-tr-box">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="formState.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="营业部/销售" prop="sellerId">
            <all-user-for-depart
              style="width: 100%"
              :props="{
                emitPath: false,
              }"
              v-model="formState.sellerId"
              placeholder="请选择营业部/销售"
            />
          </el-form-item>
        </div>
        <div class="flex form-tr-box">
          <el-form-item label="有效期" prop="validTime">
            <el-date-picker
              style="width: 235px"
              v-model="formState.validTime"
              type="daterange"
              range-separator="至"
              start-placeholder="选择日期"
              end-placeholder="选择日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="所属公司" prop="company">
            <el-input
              v-model="formState.company"
              placeholder="请输入所属公司"
            />
          </el-form-item>
        </div>
        <div class="form-tr-box auth-box">
          <div class="auth-box-label">
            <span class="text">权限</span>
            <span v-if="$route.path !== '/customer/userAdd'">
              <span style="color: var(--el-color-danger)">*</span>
              <span>用户状态</span>
              <el-switch
                v-model="formState.isEnabled"
                style="margin-left: 5px"
              />
            </span>
          </div>

          <PermissionTable
            :userId="$route.query.id"
            v-model:checkedIds="checkedIds"
          />
        </div>
      </el-form>
    </div>
    <div class="right-box">
      <div style="text-align: right" v-if="!isView">
        <el-button type="primary" style="width: 120px" @click="handleSave"
          >保存</el-button
        >
        <el-button
          type="primary"
          plain
          @click="$router.back()"
          style="width: 120px"
          >取消</el-button
        >
      </div>
      <!-- 操作记录 -->
      <OperationRecord />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.customer-user-edit-page {
  padding: 20px;
}
.content-box {
  --el-switch-off-color: #333 !important;
  --el-switch-on-color: #333 !important;
  flex: 1;
  margin-right: 30px;
  .form-tr-box {
    gap: 0 50px;
    margin-bottom: 20px;
    .el-form-item {
      width: 45%;
      max-width: 400px;
    }
  }
  .auth-box {
    .auth-box-label {
      max-width: 850px;
      display: flex;
      justify-content: space-between;
      .text {
        display: inline-block;
        width: 100px;
        text-align: right;
        padding-right: 12px;
        &::before {
          content: "*";
          color: var(--el-color-danger);
          margin-right: 4px;
          display: inline-block;
        }
      }
    }
  }
}
.right-box {
  width: 350px;
}
</style>