<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer>
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol"
          name="ConfigService2DirectiveForm">
          <a-row v-show="isAudit">
            <a-col :span="12">
              <a-config-provider :disabled="false">
                <a-form-item label="服务指令审核" v-bind="validateInfos.statusVal" id="ConfigServiceDirectiveForm-statusVal"
                  name="statusVal">
                  <a-select v-model:value="formData.statusVal" placeholder="请选择审核状态" style="width: 200px"
                    :disabled="false">
                    <a-select-option value="auditPass">审核通过</a-select-option>
                    <a-select-option value="auditFaild">审核不通过</a-select-option>
                  </a-select>
                </a-form-item>
              </a-config-provider>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
    <JFormContainer :disabled="disabled" style="margin-top: -30px;">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol"
          name="ConfigService2DirectiveForm">
          <a-row v-show="!isEditMedia">
            <a-col :span="12">
              <a-form-item label="分类标签" v-bind="validateInfos.instructionTagId"
                id="ConfigServiceDirectiveForm-instructionTagId" name="instructionTagId">
                  {{formData.instructionTag}}
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="服务类别" v-bind="validateInfos.categoryId" id="ConfigServiceDirectiveForm-categoryId"
                name="categoryId">
                  {{formData.category}}
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="服务类型" v-bind="validateInfos.typeId" id="ConfigServiceDirectiveForm-typeId"
                name="typeId">
                  {{formData.type}}
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="服务指令名称" v-bind="validateInfos.directiveName"
                id="ConfigServiceDirectiveForm-directiveName" name="directiveName">
                  {{formData.directiveName}}
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="收费价格(元)" v-bind="validateInfos.tollPrice" id="ConfigServiceDirectiveForm-tollPrice"
                name="tollPrice">
                  {{formData.tollPrice}}
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="提成价格(元)" v-bind="validateInfos.comPrice" id="ConfigServiceDirectiveForm-comPrice"
                name="comPrice">
                  {{formData.comPrice}}
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="医保报销" v-bind="validateInfos.izReimbursement"
                id="ConfigServiceDirectiveForm-izReimbursement" name="izReimbursement">
                  {{formData.izReimbursement=='1'?'报销':'不报销'}}
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="机构优惠" v-bind="validateInfos.izPreferential"
                id="ConfigServiceDirectiveForm-izPreferential" name="izPreferential">
                  {{formData.izPreferential=='1'?'参与':'不参与'}}
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="周期类型" v-bind="validateInfos.cycleType" id="ConfigServiceDirectiveForm-cycleType"
                name="cycleType">
                  <span v-if="formData.cycleType=='1'">日常护理</span>
                  <span v-if="formData.cycleType=='2'">周期护理</span>
                  <span v-if="formData.cycleType=='3'">即时护理</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="服务时长(分钟)" v-bind="validateInfos.serviceDuration"
                id="ConfigServiceDirectiveForm-serviceDuration" name="serviceDuration">
                  {{formData.serviceDuration}}
              </a-form-item>
            </a-col>
          </a-row>
          <a-col :span="12">
            <a-form-item label="服务指令描述" v-bind="validateInfos.serviceContent"
              id="ConfigServiceDirectiveForm-serviceContent" name="serviceContent">
              {{formData.serviceContent}}
            </a-form-item>
          </a-col>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted, watch } 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 { JCheckbox } from '/@/components/Form';
import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
import { getValueType } from '/@/utils';
import { Form } from 'ant-design-vue';
import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
import { getFileAccessHttpUrl } from '/@/utils/common/compUtils';

const props = defineProps({
  formDisabled: { type: Boolean, default: false },
  formData: { type: Object, default: () => ({}) },
  formBpm: { type: Boolean, default: true },
});
const bodyTagDictCode = ref(`nu_config_body_tag,tag_name,id,1=2`)
const emotionTagDictCode = ref(`nu_config_emotion_tag,tag_name,id,1=2`)
const formRef = ref();
const useForm = Form.useForm;
const emit = defineEmits(['register', 'ok']);
const formData = reactive<Record<string, any>>({
  id: '',
  categoryId: '',
  typeId: '',
  instructionTagId: '',
  directiveName: '',
  tollPrice: 0,
  comPrice: 0,
  izReimbursement: '0',
  izPreferential: '0',
  chargingFrequency: '',
  cycleType: '',
  sort: 99,
  serviceContent: '',
  serviceDuration: '5',
  izEnabled: '0',
  createBy: '',
  createTime: '',
  updateBy: '',
  updateTime: '',
  mp3File: '',
  mp4File: '',
  previewFile: '',
  immediateFile: '',
  status: '',
  statusVal: undefined,
  sysOrgCode: undefined,
  instructionTag:'',
  category:'',
  type:'',
});
const { createMessage } = useMessage();
const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 8 } });
const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
const confirmLoading = ref<boolean>(false);
const isEditMedia = ref(false)
const isAudit = ref(false)
//表单验证
const validatorRules = reactive({
});
const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
// 表单禁用
const disabled = computed(() => {
  if (props.formBpm === true) {
    if (props.formData.disabled === false) {
      return false;
    } else {
      return true;
    }
  }
  return props.formDisabled;
});
const categoryDictCode = ref('')
const typeDictCode = ref('')
// 计算属性：是否可以上传预览图片
const canUploadPreviewImage = computed(() => {
  return formData.instructionTagId &&
    formData.categoryId &&
    formData.typeId &&
    formData.directiveName &&
    formData.cycleType;
});

//分类标签名称
const instructionComDictCode = ref([])
function upInstructionDictCode(v_) {
  instructionComDictCode.value = v_
}
//服务类别名称
const categoryComDictCode = ref([])
function upCategoryDictCode(v_) {
  categoryComDictCode.value = v_

}
//服务类型名称
const typeComDictCode = ref([])
function upTypeDictCode(v_) {
  typeComDictCode.value = v_

}
//周期类型名称
const cycleTypeComDictCode = ref([])
function upCycleTypeDictCode(v_) {
  cycleTypeComDictCode.value = v_

}

watch([instructionComDictCode, categoryComDictCode, typeComDictCode, cycleTypeComDictCode], () => {
  // 当这些字典数据变化时，强制重新计算 directiveBizPath
}, { deep: true });

const directiveBizPath = computed(() => {
  if (!canUploadPreviewImage.value) return '';

  // 获取各个字段的字典值
  const instructionTagName_ = instructionComDictCode.value.filter(d => d.value == formData.instructionTagId)?.[0]?.label;
  const categoryName_ = categoryComDictCode.value.filter(d => d.value == formData.categoryId)?.[0]?.label;
  const typeName_ = typeComDictCode.value.filter(d => d.value == formData.typeId)?.[0]?.label;
  const cycleTypeName_ = cycleTypeComDictCode.value.filter(d => d.value == formData.cycleType)?.[0]?.label;

  // 构建路径
  return 'directive/' + `${instructionTagName_}/${categoryName_}/${typeName_}/${formData.directiveName}/${cycleTypeName_}`;
});

watch(
  () => formData.instructionTagId,
  (newInstructionTagId) => {
    if (!newInstructionTagId) {
      formData.categoryId = ''
      formData.typeId = ''
      categoryDictCode.value = 'nu_config_service_category,category_name,id,1=2';
    } else {
      categoryDictCode.value = `nu_config_service_category,category_name,id,del_flag = 0 and iz_enabled = 0 and iz_enabled = 0 and instruction_id = '${newInstructionTagId}' order by sort asc`;
    }
  }
);
watch(
  () => formData.categoryId,
  (newCategoryId) => {
    if (!newCategoryId) {
      formData.typeId = ''
      typeDictCode.value = 'nu_config_service_type,type_name,id,1=2';
    } else {
      typeDictCode.value = `nu_config_service_type,type_name,id,del_flag = 0 and iz_enabled = 0 and category_id = '${newCategoryId}' order by sort asc`;
    }
  }
);
/**
 * 新增
 */
function add() {
  edit({});
}

/**
 * 编辑
 * isEditMedia_是否为编辑指令资源 （隐藏业务字段）
 * isAudit_是否为服务指令那个审核 （隐藏业务字段）
 */
function edit(record, isEditMedia_ = false, isAudit_ = false) {
  console.log("🌊 ~ edit ~ record:", record)
  if (!!record.bodyTags) {
    // 将逗号分隔的字符串转换为 "id = 'id1' or id = 'id2'" 格式
    const bodyTagConditions = record.bodyTags.split(',')
      .map(id => `id = '${id}'`)
      .join(' or ');
    bodyTagDictCode.value = `nu_config_body_tag,tag_name,id,del_flag = 0 and iz_enabled = 0 ` +
      (bodyTagConditions ? ` and (${bodyTagConditions})` : '') +
      ` order by sort asc`;
  }
  if (!!record.emotionTags) {
    // 将逗号分隔的字符串转换为 "id = 'id1' or id = 'id2'" 格式
    const emotionTagConditions = record.emotionTags.split(',')
      .map(id => `id = '${id}'`)
      .join(' or ');
    emotionTagDictCode.value = `nu_config_emotion_tag,tag_name,id,del_flag = 0 and iz_enabled = 0 ` +
      (emotionTagConditions ? ` and (${emotionTagConditions})` : '') +
      ` order by sort asc`;
  }
  isEditMedia.value = isEditMedia_
  isAudit.value = isAudit_
  formData.bodyTags = ''
  formData.emotionTags = ''
  nextTick(() => {
    resetFields();
    const tmpData = {};
    Object.keys(formData).forEach((key) => {
      if (record.hasOwnProperty(key)) {
        tmpData[key] = record[key]
      }
    })
    //赋值
    Object.assign(formData, tmpData);
  });
}



defineExpose({
  add,
  edit,
});
</script>

<style lang="less" scoped>
.antd-modal-form {
  padding: 14px;
}
</style>
