<template>
  <!-- Modal -->
  <a-modal
    v-model:visible="modalVisible"
    fullscreen
    :title="title"
    title-align="start"
    :footer="false"
    @cancel="handleClose"
  >
    <a-form
      :model="modalForm"
      ref="modalFormRefConfig"
      :auto-label-width="true"
      :rules="rules"
    >
      <div class="titlebox" style="margin-bottom: 35px">
        <div class="bar"></div>
        <div class="name">随访包配置信息</div>
      </div>

      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item field="doctor_id" label="选择医生：">
            <a-select
              v-model="modalForm.doctor_id"
              placeholder="请选择医生"
              allow-search
              :loading="loading"
              @search="handleGetDoctor"
              @change="changeDoctor"
            >
              <a-option
                v-for="item in doctorList"
                :key="item.doctor_id"
                :value="item.doctor_id"
                :label="item.user_name"
              >
                {{ item.user_name }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item field="monthly_frequency" label="每月次数：">
            <div class="row">
              <a-input-number
              v-model="modalForm.monthly_frequency"
              :style="{ width: '320px' }"
              placeholder="请输入每月次数"
              class="input-demo-num"
              :step="1"
              :precision="0"
              :min="0"
            />
            <span>0表示不限次数</span>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item field="service_rounds" label="每次问诊回合数：">
            <div class="row">
              <a-input-number
              v-model="modalForm.service_rounds"
              :style="{ width: '320px' }"
              placeholder="请输入每次问诊回合数"
              class="input-demo-num "
              :step="1"
              :precision="0"
              :min="0"
            />
            <span>0表示不限回合数</span>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item
            field="doctor_config_follow_package_item"
            label="服务包明细："
          >
            <div>
              <a-space style="margin-bottom: 10px" v-if="package_data.length<4">
                <a-button type="primary" @click="addPackage">添加</a-button>
              </a-space>
              <a-table
                :columns="package_columns"
                :data="package_data"
                style="width: 100%"
                :pagination="false"
              >
                <template #service_period="{ record }">
                  <a-select
                    v-model="record.service_period"
                    placeholder="请选择周期"
                  >
                    <a-option :key="30" :value="30" label="30" :disabled="selectData.includes(30)">30 </a-option>
                    <a-option :key="90" :value="90" label="90" :disabled="selectData.includes(90)">90 </a-option>
                    <a-option :key="180" :value="180" label="180" :disabled="selectData.includes(180)">180 </a-option>
                    <a-option :key="360" :value="360" label="360" :disabled="selectData.includes(360)">360 </a-option>
                  </a-select>
                </template>
                <template #service_price="{ record }">
                  <div class="box" >
                    <a-input-number v-model="record.service_price" :min="0" />
                    <span class="tips" >建议价格设置为：{{  }}
                      <span v-if="record.service_period==30">{{tuwenPrice*10*0.5.toFixed(2)}}</span>
                      <span v-else-if="record.service_period==90">{{tuwenPrice*30*0.4.toFixed(2)}}</span>
                      <span v-else-if="record.service_period==180">{{tuwenPrice*60*0.3.toFixed(2)}}</span>
                      <span v-else-if="record.service_period==360">{{ tuwenPrice*120*0.2.toFixed(2) }}</span>
                      <span v-else>单次图文*10次*0.5</span>
                    </span>
                  
                  </div>
                </template>
                <template #action="{ record }">
                  <a-button
                    type="primary"
                    status="danger"
                    @click="removePackage(record.follow_package_item_id)"
                    >删除</a-button
                  >
                </template>
              </a-table>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item field="is_enable" label="状态：">
            <a-switch
              v-model="modalForm.is_enable"
              :checked-value="1"
              :unchecked-value="0"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-divider />
    </a-form>
    <div class="titlebox">
      <div class="bar"></div>
      <div class="name">操作</div>
    </div>
    <a-row :gutter="24" style="margin-top: 35px">
      <a-col :span="24">
        <a-form-item field="" label="" no-style>
          <a-space>
            <a-button
              type="primary"
              @click="handleSubmit"
              v-has="'admin:sysVisitconfigList:save'"
              >保存</a-button
            >
          </a-space>
        </a-form-item>
      </a-col>
    </a-row>
  </a-modal>
</template>
  <script setup>
import {
  ref,
  toRefs,
  watch,
  getCurrentInstance,
  reactive,
  computed,
  defineExpose,
} from 'vue';
import {
  addVisitConfig,
  updateVisitConfig,
  getDoctorList,
} from '@/api/inquiry/service';
import { parseTime } from '@/utils/parseTime';
 import {getInquiryconfigDetail} from "@/api/inquiry/config"
const { proxy } = getCurrentInstance();
const package_data = ref([]);
const tuwenPrice=ref(null);
const props = defineProps({
  // 是否显示
  modalVisible: {
    type: Boolean,
    default: false,
  },
  id: {
    type: String,
    default: '',
  },
  modalForm: {
    type: Object,
    default: {
      user_id: '',
    },
  },
});

const title = ref('添加问诊配置');
const loading = ref(false);
const doctorList = ref([]);
const slectData=ref([]);
const handleGetDoctor = async (name = '', id = '') => {
  loading.value = true;
  const { code, data } = await getDoctorList({
    user_name: name,
    doctor_id: id,
  });
  if (code == 200) {
    doctorList.value = data;
  }
  loading.value = false;
};
const selectData= computed(() => {
  return package_data.value.map(item=>item.service_period)
})
const addPackage = () => {
  if(!modalForm.value.doctor_id){
    proxy.$message.warning('请先选择医生');
    return false
  }
  package_data.value.push({
    service_period: null,
    service_price:null,
    follow_package_item_id: new Date().getTime(),
  });
};
const removePackage = (id) => {
  let arr = package_data.value;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].follow_package_item_id == id) {
      package_data.value.splice(i, 1);
      break;
    }
  }
};

const reset = () => {
  package_data.value = [];
};
const configDetail=async()=>{
  const {code,data}=await getInquiryconfigDetail({
    inquiry_config_id:'',
    inquiry_type:1,
    inquiry_mode:1,
    doctor_id:modalForm.doctor_id
  });
  if(code==200){
    if(data.inquiry_price){
      tuwenPrice.value=data.inquiry_price;
    }else{
      proxy.$message.warning('该医生需要开启图文问诊，才能开通此服务');
    }
    let itemname = props.modalForm.doctor_config_follow_package_item;
    if (itemname) {
      package_data.value = itemname.map((item) => {
        return {
          service_period: item.service_period,
          service_price: item.service_price,
          follow_package_item_id: item.follow_package_item_id,
        };
      });
    }
  }
}
const package_columns = [
  // {
  //   title: '服务包名称',
  //   dataIndex: 'name',
  //   slotName: 'name'
  // },
  {
    title: '服务包周期(天)',
    dataIndex: 'service_period',
    slotName: 'service_period',
  },
  {
    title: '服务价格(元)',
    dataIndex: 'service_price',
    slotName: 'service_price',
  },
  {
    title: '操作',
    dataIndex: 'action',
    slotName: 'action',
  },
];
const changeDoctor=()=>{
   configDetail();
}
const { modalVisible, id, modalForm } = toRefs(props);
const emits = defineEmits(['healthVisibleChange', 'freshList']);
watch(
  () => props.id,
  (newVal, oldValval) => {
    if (props.id) {
      title.value = '修改随访包配置';
    } else {
      title.value = '添加随访包配置';
      handleGetDoctor();
    }
  },
  { immediate: true }
);
watch(
  () => props.modalForm,
  (newVal, oldValval) => {
    if (props.modalForm.doctor_inquiry_config) {
      handleGetDoctor('', props.modalForm.doctor_inquiry_config.doctor_id);
    }
  },
  { immediate: true, deep: true }
);


// Akiraka 20230210 关闭弹窗
const handleClose = () => {
  proxy.$refs.modalFormRefConfig.resetFields();
  reset();
  emits('healthVisibleChange', false);
};

const handleSubmit = () => {
  proxy.$refs.modalFormRefConfig.validate(async (valid) => {
    let data = null;
    if(package_data.value.length==0){
      proxy.$message.warning('请添加服务包明细');
      return false
    }
   for (let i = 0; i < package_data.value.length; i++) {
     if(!package_data.value[i].service_period){
       proxy.$message.warning('服务周期不能为空');
      return false
     };
     if(!package_data.value[i].service_price){
       proxy.$message.warning('服务价格不能为空');
      return false
     };
    
   }
    let { doctor_id, monthly_frequency, service_rounds, is_enable } =
      modalForm.value;
    let obj = {
      doctor_id,
      monthly_frequency,
      service_rounds,
      is_enable,
      doctor_config_follow_package_item: package_data.value,
    };
    if (!valid) {
      if (props.id) {
        data = await updateVisitConfig(props.id, obj);
      } else {
        data = await addVisitConfig(obj);
      }
      if (data.code == 200) {
        props.id
          ? proxy.$message.success('修改成功')
          : proxy.$message.success('添加成功');
        emits('freshList', '');
      }
      handleClose();
    } else {
      console.log(valid);
      proxy.$message.error('表单校验失败');
      //done(false);
    }
  });
};

const rules = {
  monthly_frequency: [{ required: true, message: '请选择每月次数' }],
  doctor_id: [{ required: true, message: '请选择医生' }],
  service_rounds: [{ required: true, message: '请输入服务回合数' }],
  is_enable: [{ required: true, message: '请选择状态' }],
  //doctor_config_follow_package_item:[{type:Array, required: true, message: '请添加服务包明细' }]
};

defineExpose({
  reset,
  changeDoctor
});
</script>
  <style scoped>
  .row{
    display: flex;
   
    flex-direction: column;
  }
  .row span{
    font-size: 12px;
  
    color:#999;
  } 
  .box{
    margin-top: 20px;
  }
  .box.active{
    margin-top: 0px;
  }
 
  .tips{
    color:red;
    font-size: 12px;
  }
</style>