<!--
 * @Author: xiejiang
 * @Date: 2024-12-01 10:26:11
 * @LastEditors: xiejiang
 * @LastEditTime: 2024-12-11 23:10:28
 * @Description: 新增编辑角色
 * Copyright（c）2024 by 好老师教育科技有限公司 All right Reserved.
-->
<template>
  <div class="bg-white h-full p-[12px] institution-edit">
    <Back />
    <t-form ref="formRef" label-align="top" class="form-class !pt-[24px]" :rules="rules" :data="formData">
      <t-form-item label="机构名称" name="companyName">
        <t-input maxlength="20" v-model="formData.companyName" placeholder="请输入机构名称"> </t-input>
      </t-form-item>
      <t-form-item label="机构类型" name="companyType">
        <t-radio-group v-model="formData.companyType">
          <t-radio v-for="v in dictDatas" :key="v.dictDataId" :value="v.dictDataId">{{ v.valueName }}</t-radio>
        </t-radio-group>
      </t-form-item>
      <div class="info">
        <PageTitle title="机构管理员设置" class="mb-[24px]" />
        <t-form-item label="管理员姓名" name="adminUserName">
          <t-input maxlength="20" v-model="formData.adminUserName" placeholder="请输入管理员姓名"> </t-input
        ></t-form-item>
        <t-form-item label="管理员手机号码" name="adminUserMobile">
          <t-input
            maxlength="11"
            @input="
              (v: any) => {
                formData.adminUserMobile = v.target.value.replace(/[^0-9]/g, '')
              }
            "
            v-model="formData.adminUserMobile"
            placeholder="请输入管理员手机号码"
          >
          </t-input
        ></t-form-item>
      </div>

      <t-form-item label="机构服务结束时间" name="serviceTerminationTime" class="position-relative">
        <template #label>
          <div style="display: inline-flex">
            <span>机构服务结束时间</span>
            <p class="text-[var(--td-warning-color-6)] m-[0] text-[12px] ml-[8px]">
              (机构服务的结束时间为该日期当日23:59:59)
            </p>
          </div>
        </template>
        <t-date-picker
          class="w-full"
          v-model="formData.serviceTerminationTime"
          clearable
          type="date"
          :disable-date="{ before: dayjs().subtract(1, 'day').format('YYYY-MM-DD') }"
          placeholder="请选择时间"
        />
      </t-form-item>

      <t-form-item label="机构备注" name="remark">
        <t-textarea :maxlength="200" v-model="formData.remark" placeholder="请输入内容"> </t-textarea>
      </t-form-item>
    </t-form>

    <FooterFixBtn>
      <template #button>
        <t-button theme="primary" :loading="submitLoading" @click="handleConfirm"> 保存</t-button></template
      >
    </FooterFixBtn>
  </div>
</template>

<script setup lang="ts" name="institution-edit">
import { useRoute, useRouter } from 'vue-router'
import { FormProps, FormInstanceFunctions, CustomValidator } from 'tdesign-vue-next'
import dayjs from 'dayjs'
import { useBasic } from '@/hooks/useBasic'
import { isPhoneNumber } from '@/utils'
import { ReqCompany } from '@/api/interface/institution/index'
import { getDetail, postCompanySave, postCompanyUpdate } from '@/api/modules/institution/index'
import { ResDictionary } from '@/api/interface/dectionory/index'
import { getGetDictDataByName } from '@/api/modules/dectionory/index'

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

const { setBreadcrumb } = useBasic()

const submitLoading = ref(false)

const formRef = useTemplateRef<FormInstanceFunctions>('formRef')
const formData = reactive<ReqCompany>({
  companyName: '',
  companyType: '',
  adminUserMobile: '',
  adminUserName: '',
  remark: '',
  companyId: '',
  serviceTerminationTime: ''
})

const validateTelePhone: CustomValidator = val => {
  if (!val) {
    return {
      result: false,
      message: '请输入管理员手机号码！',
      type: 'error'
    }
  }
  if (!isPhoneNumber(val)) {
    return {
      result: false,
      message: '请输入正确的手机号码！',
      type: 'error'
    }
  } else {
    return {
      result: true,
      message: '',
      type: 'success'
    }
  }
}

const rules: FormProps['rules'] = {
  companyName: [
    {
      required: true,
      message: '请填写机构名称！',
      trigger: 'blur'
    }
  ],
  adminUserName: [
    {
      required: true,
      message: '请输入管理员姓名！',
      trigger: 'blur'
    }
  ],
  adminUserMobile: [
    {
      validator: validateTelePhone
    }
  ],
  serviceTerminationTime: [
    {
      required: true,
      message: '请选择机构服务结束时间！',
      trigger: 'change'
    }
  ],
  companyType: [
    {
      required: true,
      message: '请选择机构类型！',
      trigger: 'change'
    }
  ]
}

const getData = () => {
  getDetail({ companyId: route.query.companyId as string }).then(res => {
    formData.companyName = res.data.companyName
    formData.companyType = res.data.companyType
    formData.adminUserMobile = res.data.adminUserMobile
    formData.adminUserName = res.data.adminUserName
    formData.remark = res.data.remark
    formData.serviceTerminationTime = res.data.serviceTerminationTime
    formData.companyId = res.data.companyId
  })
}

// 获取机构类型
const dictDatas = ref<ResDictionary[]>([])
const getDictData = () => {
  getGetDictDataByName({ dictName: '机构类型' }).then(res => {
    dictDatas.value = res.data
  })
}

const hasTime = (timeString: string): boolean => {
  // 正则表达式匹配包含时分秒的时间格式
  const timeFormatRegex = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/
  return timeFormatRegex.test(timeString)
}

// 确认
const handleConfirm = () => {
  formRef.value?.validate().then(val => {
    if (val === true) {
      submitLoading.value = true
      const sumit = route.query.companyId ? postCompanyUpdate : postCompanySave

      let form = { ...formData }
      form.serviceTerminationTime = hasTime(formData.serviceTerminationTime as string)
        ? formData.serviceTerminationTime
        : formData.serviceTerminationTime + ' 23:59:59'
      sumit(form)
        .then(() => {
          MessagePlugin.success('保存成功')
          router.push({ name: 'institution' })
        })
        .finally(() => {
          submitLoading.value = false
        })
    }
  })
}

onMounted(() => {
  setBreadcrumb([
    {
      title: '客户中心'
    },
    {
      title: '机构管理',
      name: 'institution'
    },
    {
      title: route.query.companyId ? '修改机构' : '添加机构'
    }
  ])
  getDictData()
  if (route.query.companyId) {
    getData()
  }
})
</script>

<style lang="less" scoped>
.institution-edit {
  max-height: calc(100% - 76px);

  .form-class {
    margin: 0 auto;
    max-width: 500px;

    .info {
      padding: 20px 16px;
      border-radius: 3px;
      margin-bottom: 24px;
      background-color: var(--td-gray-color-1);
    }

    .times {
      position: absolute;
      left: 0;
      top: 44px;
    }
  }

  :deep(.t-radio__label) {
    color: var(--td-font-gray-2);
  }
}
</style>
