<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer  class="advisoryClass">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="NuBizAdvisoryInfoForm">
          <a-row>
            <a-col :span="24">
              <a-form-item label="选择机构" v-bind="validateInfos.sysOrgCode" id="NuBizAdvisoryInfoForm-sysOrgCode" name="sysOrgCode">
                <a-radio-group v-model:value="formData.sysOrgCode" @change="handleChangeRadio">
                  <template v-for="item in institutionsSource" :key="`${item.id}`">
                    <a-radio :value="item.id">
                      {{ item.departName }}
                    </a-radio>
                  </template>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="咨询类型" v-bind="validateInfos.advisoryType" id="NuBizAdvisoryInfoForm-advisoryType" name="advisoryType">
                <j-dict-select-tag type='radio' v-model:value="formData.advisoryType" dictCode="advisory_type" placeholder="请选择咨询类型"  allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="咨询人姓名" v-bind="validateInfos.name" id="NuBizAdvisoryInfoForm-name" name="name">
                <a-input v-model:value="formData.name" placeholder="请输入咨询人姓名"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="性别" v-bind="validateInfos.sex" id="NuBizAdvisoryInfoForm-sex" name="sex">
                <j-dict-select-tag type='radio' v-model:value="formData.sex" dictCode="sex" placeholder="请选择性别"  allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="联系电话" v-bind="validateInfos.tel" id="NuBizAdvisoryInfoForm-tel" name="tel">
                <a-input v-model:value="formData.tel" placeholder="请输入联系电话"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <div v-if="formData.advisoryType == '1'">
              <a-col :span="24">
                <a-form-item label="老人姓名" v-bind="validateInfos.oldManName" id="NuBizAdvisoryInfoForm-oldManName" name="oldManName">
                  <a-input v-model:value="formData.oldManName" placeholder="请输入老人姓名"  allow-clear ></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="老人年龄" v-bind="validateInfos.oldManAge" id="NuBizAdvisoryInfoForm-oldManAge" name="oldManAge">
                  <a-input v-model:value="formData.oldManAge" placeholder="请输入老人年龄"  allow-clear ></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="医保类型" v-bind="validateInfos.medicalInsuranceType" id="NuBizAdvisoryInfoForm-medicalInsuranceType" name="medicalInsuranceType">
                  <j-dict-select-tag type='radio' v-model:value="formData.medicalInsuranceType" dictCode="medical_insurance_type" placeholder="请选择性别"  allow-clear />
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="老人性别" v-bind="validateInfos.oldManSex" id="NuBizAdvisoryInfoForm-oldManSex" name="oldManSex">
                  <j-dict-select-tag type='radio' v-model:value="formData.oldManSex" dictCode="sex" placeholder="请选择性别"  allow-clear />
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="报销类型" v-bind="validateInfos.reimbType" id="NuBizAdvisoryInfoForm-reimbType" name="reimbType">
                  <j-dict-select-tag type='radio' v-model:value="formData.reimbType" dictCode="reimb_type" placeholder="请选择性别"  allow-clear />
                </a-form-item>
              </a-col>
            </div>
            <a-col :span="24" style="text-align: center;">
              <a-button type="primary" @click="handleSubmit()">提交</a-button>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { getValueType } from '/@/utils';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { useGlobSetting } from "/@/hooks/setting";
  import { useRouter } from 'vue-router'
  import axios from 'axios';

  const router = useRouter();
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const glob = useGlobSetting()
  const institutionsSource = ref([]);
  const openId = ref<string>('公众号openId');
  const wechatName = ref<string>('公众号姓名');
  const formData = reactive<Record<string, any>>({
    id: '',
    name: '',   
    sex: '1',   
    sysOrgCode: '',
    tel: '',   
    advisoryType: '1',   
    status: '1',   
    content: '',   
    serverUrl: '',
    openId: '',
    wechatName: '',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    name: [{ required: true, message: '请输入姓名!' }],
    sysOrgCode: [{ required: true, message: '请选择入住机构!' }],
    advisoryType: [{ required: true, message: '请选择咨询类型!' }],
    tel: [{ required: true, message: '请输入联系电话!' }, { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '联系电话错误!' }],
    sex: [{ required: true, message: '请选择性别!' }],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

//选中机构后获取serverUrl地址
  function handleChangeRadio(item){
    const checkId = item.target.value;
    const checkData = institutionsSource.value.filter(item => item.id === checkId);
    if(checkData.length>0){
      const serverUrl = checkData[0].serverUrl;
      formData.serverUrl = serverUrl;
    }
    console.log('formData--->',formData);
  }

//提交信息
  async function handleSubmit() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    //时间格式化
    let model = formData;
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    model.openId = openId.value;
    model.wechatName = wechatName.value;
    model.status = '1';//强制在提交时把status置为1 审核中
    console.log('model--->',model);
    
    if(model.advisoryType == '1'){
      if(!model.oldManName){

        return createMessage.error("老人姓名不能为空");
      }
    }

    const serverUrl = formData.serverUrl;
    axios.post(serverUrl+"/h5Api/nuBizAdvisoryInfo/edit",model).then(response => {
      var data = response.data;
      if(data.code === 200){
        createMessage.success("操作成功");
        //跳转到信息页面
        router.push({ path: "/h5/advisoryInfo" });
      }
    }).catch(error => {
      console.error(error);
    });
  }

  function getWechatInfo(){
    
    const institutionsUrl = glob.domainUrl+"/sys/sysDepart/queryInstitutionsList";
    axios.get(institutionsUrl).then(response => {
      institutionsSource.value = response.data;
    }).catch(error => {
      console.error(error);
    });
    
    //获取是否注册了信息
    const getWechartInfoUrl = glob.domainUrl+"/h5Api/nuBizAdvisoryInfo/queryByOpenId?openId="+openId.value;
    axios.get(getWechartInfoUrl).then(response => {
      const tmpData = response.data.result;
      Object.assign(formData, tmpData);
    }).catch(error => {
      console.error(error);
    });

  }
  //自动加载
  onMounted(() => {
    //TODO 获取微信公众号信息
    getWechatInfo()
  });
 
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
  .advisoryClass{
    background-image: url(/@/assets/images/advisory.jpg);
      background-size: cover; /* 确保图片覆盖整个元素 */
  background-position: center; /* 将图片居中显示 */
  min-height: 100vh; /* 确保至少为视口高度 */
  }
</style>
