<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol"
          name="ConfigServiceDirectiveForm">
          <a-row>
            <a-col :span="12">
              <a-form-item label="服务类别" v-bind="validateInfos.categoryId" id="ConfigServiceDirectiveForm-categoryId"
                name="categoryId">
                <j-dict-select-tag type="list" v-model:value="formData.categoryId"
                  :dictCode="`config_service_category,category_name,id,del_flag = 0 order by sort asc`"
                  placeholder="请选择服务类别" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="服务类型" v-bind="validateInfos.typeId" id="ConfigServiceDirectiveForm-typeId"
                name="typeId">
                <j-dict-select-tag type="list" v-model:value="formData.typeId" :dictCode="typeDictCode"
                  placeholder="请选择服务类型" allowClear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="分类标签" v-bind="validateInfos.instructionTagId"
                id="ConfigServiceDirectiveForm-instructionTagId" name="instructionTagId">
                <j-dict-select-tag v-model:value="formData.instructionTagId" dictCode="instruction_tag"
                  placeholder="请选择分类标签" allowClear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="服务指令名称" v-bind="validateInfos.directiveName"
                id="ConfigServiceDirectiveForm-directiveName" name="directiveName">
                <a-input v-model:value="formData.directiveName" placeholder="请输入服务指令名称" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <!-- <a-col :span="12">
              <a-form-item label="收费价格(元)" v-bind="validateInfos.tollPrice" id="ConfigServiceDirectiveForm-tollPrice"
                name="tollPrice">
                <a-input-number v-model:value="formData.tollPrice" placeholder="请输入收费价格" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="提成价格(元)" v-bind="validateInfos.comPrice" id="ConfigServiceDirectiveForm-comPrice"
                name="comPrice">
                <a-input-number v-model:value="formData.comPrice" placeholder="请输入提成价格" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="医保报销" v-bind="validateInfos.izReimbursement"
                id="ConfigServiceDirectiveForm-izReimbursement" name="izReimbursement">
                <j-dict-select-tag type='radio' v-model:value="formData.izReimbursement" dictCode="med_ins_reimb"
                  allowClear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="机构优惠" v-bind="validateInfos.izPreferential"
                id="ConfigServiceDirectiveForm-izPreferential" name="izPreferential">
                <j-dict-select-tag type='radio' v-model:value="formData.izPreferential"
                  dictCode="institutional_discount" allowClear />
              </a-form-item>
            </a-col> -->
            <!-- <a-col :span="12">
              <a-form-item label="收费频次" v-bind="validateInfos.chargingFrequency"
                id="ConfigServiceDirectiveForm-chargingFrequency" name="chargingFrequency">
                <j-dict-select-tag type="list" v-model:value="formData.chargingFrequency" dictCode="billing_frequency"
                  placeholder="请选择收费频次" allowClear />
              </a-form-item>
            </a-col> -->
            <a-col :span="12">
              <a-form-item label="周期类型" v-bind="validateInfos.cycleType" id="ConfigServiceDirectiveForm-cycleType"
                name="cycleType">
                <j-dict-select-tag type="list" v-model:value="formData.cycleType" dictCode="period_type"
                  placeholder="请选择周期类型" allowClear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="服务时长（分钟）" v-bind="validateInfos.serviceDuration"
                id="ConfigServiceDirectiveForm-serviceDuration" name="serviceDuration">
                <a-input-number v-model:value="formData.serviceDuration" :min="5" :max="55" :step="5"
                  placeholder="请输入服务时长（分钟）" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="服务说明" v-bind="validateInfos.serviceContent"
                id="ConfigServiceDirectiveForm-serviceContent" name="serviceContent">
                <a-textarea v-model:value="formData.serviceContent" :rows="2" placeholder="请输入服务说明" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <!-- <a-col :span="12">
              <a-form-item label="排序" v-bind="validateInfos.sort" id="ConfigServiceDirectiveForm-sort" name="sort">
                <a-input-number v-model:value="formData.sort" placeholder="请输入排序" style="width: 100%" />
              </a-form-item>
            </a-col> -->
            <a-col :span="24">
              <a-form-item label="指令标签" id="ConfigServiceDirectiveForm-typeId" :labelCol="labelCol2"
                :wrapperCol="wrapperCol2" name="typeId">
                <JCheckbox v-model:value="formData.tags"
                  :dictCode="`config_directive_tag,tag_name,id,del_flag = 0 order by sort asc`" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="是否启用" v-bind="validateInfos.izEnabled" id="ConfigServiceDirectiveForm-izEnabled"
                name="izEnabled">
                <j-dict-select-tag type='radio' v-model:value="formData.izEnabled" dictCode="iz_enabled"
                  placeholder="请选择是否启用"  allowClear />
              </a-form-item>
            </a-col>
            <!-- <a-col :span="12">
              <a-form-item label="创建人" v-bind="validateInfos.createBy" id="ConfigServiceDirectiveForm-createBy"
                name="createBy">
                <a-input v-model:value="formData.createBy" placeholder="请输入创建人" disabled allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="创建日期" v-bind="validateInfos.createTime" id="ConfigServiceDirectiveForm-createTime"
                name="createTime">
                <a-date-picker placeholder="请选择创建日期" v-model:value="formData.createTime" showTime
                  value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" disabled allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="更新人" v-bind="validateInfos.updateBy" id="ConfigServiceDirectiveForm-updateBy"
                name="updateBy">
                <a-input v-model:value="formData.updateBy" placeholder="请输入更新人" disabled allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="更新日期" v-bind="validateInfos.updateTime" id="ConfigServiceDirectiveForm-updateTime"
                name="updateTime">
                <a-date-picker placeholder="请选择更新日期" v-model:value="formData.updateTime" showTime
                  value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" disabled allow-clear />
              </a-form-item>
            </a-col> -->
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item label="语音文件" v-bind="validateInfos.mp3File" id="ConfigServiceDirectiveForm-mp3File"
                name="mp3File">
                <j-upload v-model:value="formData.mp3File" accept=".mp3" :maxCount="1"></j-upload>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="视频文件" v-bind="validateInfos.mp4File" id="ConfigServiceDirectiveForm-mp4File"
                name="mp4File">
                <j-upload v-model:value="formData.mp4File" accept=".mp4" :maxCount="1"></j-upload>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
    <JFormContainer>
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol"
          name="ConfigServiceDirectiveForm">
          <a-row>
            <a-col :span="12" v-if="!!formData.mp3File">
              <a-form-item label="语音预览" id="ConfigServiceDirectiveForm-mp3File" name="mp3File">
                <audio controls disabled="false">
                  <source :src="getFileAccessHttpUrl(formData.mp3File)">
                </audio>
              </a-form-item>
            </a-col>
            <a-col :span="12" v-if="!!formData.mp4File" :push="!!formData.mp3File ? 0 : 12">
              <a-form-item label="视频预览" id="ConfigServiceDirectiveForm-mp4File" name="mp4File">
                <video controls>
                  <source :src="getFileAccessHttpUrl(formData.mp4File)">
                </video>
              </a-form-item>
            </a-col>
          </a-row>
        </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 { getValueType } from '/@/utils';
import { saveOrUpdate } from '../ConfigServiceDirective.api';
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 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: '',
});
const { createMessage } = useMessage();
const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 6 } });
const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
const labelCol2 = ref<any>({ xs: { span: 24 }, sm: { span: 3 } });
const wrapperCol2 = ref<any>({ xs: { span: 24 }, sm: { span: 20 } });
const confirmLoading = ref<boolean>(false);
//表单验证
const validatorRules = reactive({
  categoryId: [{ required: true, message: '请选择服务类别!' },],
  typeId: [{ required: true, message: '请选择服务类型!' },],
  instructionTagId: [{ required: true, message: '请选择分类标签!' },],
  directiveName: [{ required: true, message: '请输入服务指令名称!' },],
  tollPrice: [{ required: true, message: '请输入收费价格!' }, { pattern: /^(([0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' },],
  comPrice: [{ required: false }, { pattern: /^(([0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' },],
  izReimbursement: [{ required: true, message: '请选择是否参与医保报销!' },],
  izPreferential: [{ required: true, message: '请选择是否参与机构优惠!' },],
  // chargingFrequency: [{ required: true, message: '请选择收费频次!' },],
  cycleType: [{ required: true, message: '请选择周期类型!' },],
  // sort: [{ required: true, message: '请输入排序!' }, { pattern: /^\d+$/, message: '请输入正整数!' },],
  serviceDuration: [
    { required: true, message: '请输入服务时长（分钟）!' },
    { pattern: /^\d+$/, message: '请输入正整数!' },
    {
      validator: (_, value) => {
        if (value % 5 !== 0) {
          return Promise.reject('请输入5的倍数!');
        }
        return Promise.resolve();
      },
    },
    {
      validator: (_, value) => {
        if (value < 5 || value > 55) {
          return Promise.reject('请输入5到55之间的值!');
        }
        return Promise.resolve();
      },
    },
  ],
  izEnabled: [{ required: true, message: '请选择是否启用!' },],
});
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 typeDictCode = ref('')

watch(
  () => formData.categoryId,
  (newCategoryId) => {
    if (!newCategoryId) {
      formData.typeId = '';
      typeDictCode.value = 'config_service_type,type_name,id,del_flag = 99 order by sort asc';
    } else {
      typeDictCode.value = `config_service_type,type_name,id,del_flag = 0 and category_id = '${newCategoryId}' order by sort asc`;
    }
  }
);

/**
 * 新增
 */
function add() {
  edit({});
}

/**
 * 编辑
 */
function edit(record) {
  formData.tags = ''
  nextTick(() => {
    resetFields();
    const tmpData = {};
    Object.keys(formData).forEach((key) => {
      if (record.hasOwnProperty(key)) {
        tmpData[key] = record[key]
      }
    })
    //赋值
    Object.assign(formData, tmpData);
  });
}

/**
 * 提交数据
 */
async function submitForm() {
  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);
  }
  confirmLoading.value = true;
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  //循环数据
  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(',');
      }
    }
  }
  await saveOrUpdate(model, isUpdate.value)
    .then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        emit('ok');
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
    });
}


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

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