<script setup lang="ts">
import { ref, reactive, watch, onMounted, defineEmits, nextTick } from 'vue';
import { notification } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { branchMethod } from '@/request/api/system.api';
import { useRequest } from 'alova/client';
import { cpMedicinesMethod } from '@/request/api/dictionary.api';
import { VxeUI } from 'vxe-pc-ui';
import RemoteSelect from '@/libs/v-select-page/RemoteSelect.vue';
import { confirmOrgConfirmMethod, getConditioningSchemeDetailMethod, getAllSupplierMethod } from '@/request/api/care.api';
import type { SystemItemModel } from '@/model/care.model';
import { UploadIFile } from '@/request/api/follow.api';
import type { UploadFile } from 'ant-design-vue/es/upload/interface';
type SystemModel = Partial<SystemItemModel>;
const props = defineProps<{ data: SystemModel }>();
(notification.config as any)({
  zIndex: 10000, // 直接设置层级
});
const unitOptions = [
  { label: '袋', value: '袋' },
  { label: '包', value: '包' },
  { label: '贴', value: '贴' },
  { label: '次', value: '次' },
];
const fileList = ref<UploadFile[]>([]);
// 获取所有的机构
const branch = ref<any[]>([]);
const { loading: branchLoading } = useRequest(branchMethod).onSuccess(({ data }) => {
  const to = (data?: any[]): any[] => {
    return Array.isArray(data)
      ? data.map((item) => {
          return {
            ...item,
            value: item.id,
            key: item.id.toString(),
            children: to(item.children),
          };
        })
      : [];
  };
  branch.value = to(data);
});

const supplierOptions = ref<any[]>([]);
// 获取所有的供应商
const supplierArr = ref<any[]>([]);
supplierOptions.value = [];
function getSupplier(params: any) {
  getAllSupplierMethod(params).then((res: unknown) => {
    if (Array.isArray(res) && res.length > 0) {
      supplierArr.value = res as any[];
      supplierOptions.value = (res as any[]).map((item: any) => ({
        label: item.name,
        value: item.id,
      }));
    }
  });
}
watch(
  [() => props.data.conditioningProgramType, () => props.data.institutionId],
  ([newType, newInstitutionId]) => {
    if (newType) {
      props.data.conditioningProgramSupplierId = '';
      props.data.isOffline = null;
    }
    getSupplier({
      conditioningProgramTypes: newType ? [newType] : [],
      collaborateDeptId: newInstitutionId ? newInstitutionId : '',
    });
  },
  { immediate: true }
);
let showOffLine = ref<boolean>(false);
function getIsonline(newSupplierId: any) {
  if (!supplierArr.value?.length || !newSupplierId || !props.data?.conditioningProgramType) {
    return;
  }

  const supplier = supplierArr.value.find((item) => item.id === newSupplierId);
  if (!supplier) {
    return;
  }

  const { offlineCPTypes, onlineCPTypes } = supplier;
  const programType = props.data.conditioningProgramType;

  // 检查是否同时支持线上和线下
  const supportsOffline = offlineCPTypes?.includes(programType);
  const supportsOnline = onlineCPTypes?.includes(programType);

  if (supportsOffline && supportsOnline) {
    showOffLine.value = true;
    return;
  }

  // 设置显示状态
  showOffLine.value = false;

  // 根据支持情况设置项目类型
  if (supportsOffline) {
    props.data.isOffline = 'Y';
  } else if (supportsOnline) {
    props.data.isOffline = 'N';
  } else {
    props.data.isOffline = null;
  }
}

watch(
  () => props.data.conditioningProgramSupplierId,
  async (newSupplierId: any) => {
    if (newSupplierId) {
      await nextTick();
      if (supplierArr.value && supplierArr.value.length > 0) {
        getIsonline(newSupplierId);
      } else {
        // 如果数据还没加载，等待一段时间后重试
        setTimeout(() => {
          if (supplierArr.value && supplierArr.value.length > 0) {
            getIsonline(newSupplierId);
          }
        }, 200);
      }
    }
  }
);

// 建议频率单位
const suggestedFrequencyUnit = ref<string>('');

// 监听一口价单位变化，同步到建议频率单位
watch(
  () => props.data.cpFixedPricingRule?.convertUnit,
  (newVal) => {
    if (props.data.pricingType === '0') {
      suggestedFrequencyUnit.value = newVal || '';
    }
  }
);

// 监听建议频率单位变化，回写到一口价使用单位（保证双向一致）
watch(
  () => suggestedFrequencyUnit.value,
  (newVal) => {
    if (props.data.pricingType === '0' && props.data.cpFixedPricingRule && newVal) {
      props.data.cpFixedPricingRule.convertUnit = newVal;
    }
  }
);

// 监听计价规则变化，同步建议频率单位
watch(
  () => props.data.pricingType,
  (val) => {
    if (val === '0') {
      // 一口价模式：建议频率单位与一口价单位保持一致
      if (props.data.cpFixedPricingRule?.convertUnit) {
        suggestedFrequencyUnit.value = props.data.cpFixedPricingRule.convertUnit;
      } else {
        suggestedFrequencyUnit.value = '';
      }
    } else if (val === '1') {
      // 按穴位模式：建议频率单位默认为"次"
      suggestedFrequencyUnit.value = '次';
    }
  }
);
const uploadProps = reactive({ showRemoveIcon: true });
function customUpload(e: any) {
  // uploadApi 你的二次封装上传接口
  UploadIFile(e.file)
    .then((res) => {
      // 调用实例的成功方法通知组件该文件上传成功
      e.onSuccess(res, e);
    })
    .catch((err) => {
      // 调用实例的失败方法通知组件该文件上传失败
      e.onError(err);
    });
}
const visible = ref<boolean>(false);
const setVisible = (value: boolean): void => {
  visible.value = value;
};
const previewImg = ref<string>('');
// 预览图片
const handlePreview = async (file: UploadFile) => {
  previewImg.value = file.response?.url ?? file.thumbUrl;
  visible.value = true;
};

function removeHerb(idx: number) {
  if (Array.isArray(props.data.cpMedicines)) {
    props.data.cpMedicines.splice(idx, 1);
  }
}

function addHerb() {
  if (!Array.isArray(props.data.cpMedicines)) {
    props.data.cpMedicines = [] as any[];
  }
  (props.data.cpMedicines as any[]).push({ name: '', dosage: '' } as any);
}

function handleCancel() {
  VxeUI.modal.close('confirm-item-modal');
}

// Define emits
const emit = defineEmits<{
  (e: 'submit', data: SystemItemModel): void;
}>();

function validate(): boolean {
  const d = props.data as any;
  // 计价规则 必填
  if (d.pricingType === undefined || d.pricingType === null || d.pricingType === '') {
    notification.error({
      message: '请选择计价规则',
      description: '请选择计价规则',
    });
    return false;
  }
  // 单价 必填（当一口价时）
  if (d.pricingType === '0') {
    const unitPrice = d.cpFixedPricingRule?.unitPrice;
    if (unitPrice === undefined || unitPrice === null || unitPrice === '') {
      notification.error({
        message: '请填写单价',
        description: '请填写单价',
      });
      return false;
    }
    // 计价单位 必填
    if (!d.cpFixedPricingRule?.pricingUnit) {
      notification.error({
        message: '请填写计价单位',
        description: '请填写计价单位',
      });
      return false;
    }
    // 转换剂量 必填
    if (!d.cpFixedPricingRule?.convertDose) {
      notification.error({
        message: '请填写转换剂量',
        description: '请填写转换剂量',
      });
      return false;
    }
    // 转换单位 必填
    if (!d.cpFixedPricingRule?.convertUnit) {
      notification.error({
        message: '请选择转换单位',
        description: '请选择转换单位',
      });
      return false;
    }
  }
  // 穴位/经络/部位 范围 必填（当动态计价时）
  if (d.pricingType === '1') {
    const rules = d.cpDynamicPricingRule;
    if (!Array.isArray(rules) || rules.length < 2) {
      notification.error({
        message: '请完善穴位/经络/部位的计价规则',
        description: '请完善穴位/经络/部位的计价规则',
      });
      return false;
    }

    // 验证计价1
    const rule1 = rules[0];
    if (!rule1 || rule1.min === undefined || rule1.min === '') {
      notification.error({
        message: '请填写计价1的穴位/经络/部位范围',
        description: '请填写计价1的穴位/经络/部位范围',
      });
      return false;
    }
    if (rule1.priceType === undefined || rule1.priceType === null || rule1.priceType === '') {
      notification.error({
        message: '请选择计价1的计价类型',
        description: '请选择计价1的计价类型',
      });
      return false;
    }
    if (!rule1.price || rule1.price === '') {
      notification.error({
        message: '请填写计价1的价格',
        description: '请填写计价1的价格',
      });
      return false;
    }

    // 验证计价2
    const rule2 = rules[1];
    if (!rule2 || rule2.max === undefined || rule2.max === '') {
      notification.error({
        message: '请填写计价2的穴位/经络/部位范围',
        description: '请填写计价2的穴位/经络/部位范围',
      });
      return false;
    }
    if (rule2.priceType === undefined || rule2.priceType === null || rule2.priceType === '') {
      notification.error({
        message: '请选择计价2的计价类型',
        description: '请选择计价2的计价类型',
      });
      return false;
    }
    if (!rule2.price || rule2.price === '') {
      notification.error({
        message: '请填写计价2的价格',
        description: '请填写计价2的价格',
      });
      return false;
    }
  }
  // 机构 必填
  if (!d.institutionId) {
    notification.error({
      message: '请选择机构名称',
      description: '请选择机构名称',
    });
    return false;
  }
  // 供应商 不必填
  return true;
}

function handleOk() {
  if (!validate()) return;
  if (showOffLine.value && !props.data.isOffline) {
    props.data.isOffline = 'N';
  }
  // 同步建议频率单位到一口价使用单位
  if (props.data.pricingType === '0' && props.data.cpFixedPricingRule && suggestedFrequencyUnit.value) {
    props.data.cpFixedPricingRule.convertUnit = suggestedFrequencyUnit.value;
  }
  props.data.photo = fileList.value[0]?.response?.url || fileList.value[0]?.url || '';
  confirmOrgConfirmMethod(props.data as SystemItemModel).then(() => {
    console.log(props.data, 'props.data');
    console.log(fileList.value, 'fileList.value111111');
    emit('submit', props.data as SystemItemModel);
    VxeUI.modal.close('confirm-item-modal');
    notification.success({
      message: '提交成功',
      description: '提交成功',
    });
  });
}
const isOffline = ref<boolean>(false);
onMounted(async () => {
  console.log(props.data, 'props.data11111');
  if (props.data.id) {
    const res = await getConditioningSchemeDetailMethod(props.data);
    Object.assign(props.data, res);
    getIsonline(props.data.conditioningProgramSupplierId);
    // 初始化建议频率单位
    suggestedFrequencyUnit.value = res.cpFixedPricingRule?.convertUnit || '';
  } else {
    // 如果没有数据，从现有数据中获取
    suggestedFrequencyUnit.value = props.data.cpFixedPricingRule?.convertUnit || '';
  }
  
  fileList.value = props.data?.photo
    ? [
        {
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: props.data?.photo,
          thumbUrl: props.data?.photo,
        },
      ]
    : [];
  isOffline.value = props.data.isOffline === 'Y';
});
// 安全获取弹窗容器
function getSafePopupContainer(triggerNode: HTMLElement) {
  return document?.body || triggerNode?.parentNode || triggerNode;
}

// 处理机构选择变化
function handleInstitutionChange(value: string | number, node: any) {
  props.data.institutionId = value;
  props.data.institutionName = node?.label || node?.title || '';
}
</script>

<template>
  <div class="form-container">
    <div class="form-row">
      <label>项目名称：</label>
      <span>{{ data.name }}</span>
    </div>
    <div class="form-row">
      <label>方案类型：</label>
      <div>{{ data.conditioningProgramType }}</div>
    </div>
    <div class="form-row">
      <label>商品类型：</label>
      <div>{{ data.sellType === '1' ? '实体商品' : data.sellType === '2' ? '线下服务' : data.sellType === '3' ? '线上权益' : '-' }}</div>
    </div>
    <div class="form-row">
      <label><span class="required-star">*</span>计价规则：</label>
      <div>{{ data.pricingType === '0' ? '一口价' : '按穴位/经络/部位' }}</div>
    </div>
    <div class="form-row" v-if="data.pricingType === '0'">
      <label><span class="required-star">*</span>单价：</label>
      <a-input v-model:value="data.cpFixedPricingRule!.unitPrice" placeholder="请输入" style="width: 100px; margin-left: 8px" />
      <span style="margin-left: 20px">元</span>
      <span style="margin-left: 20px">计价单位：</span>
      <a-input v-model:value="data.cpFixedPricingRule!.pricingUnit" placeholder="请输入" style="width: 100px; margin-left: 8px" />
      <span style="margin-left: 20px">相当于</span>
      <a-input v-model:value="data.cpFixedPricingRule!.convertDose" placeholder="请输入" style="width: 100px; margin-left: 8px" />
      <vxe-select v-model="data.cpFixedPricingRule!.convertUnit" style="width: 100px; margin-left: 8px" :options="unitOptions" placeholder="请选择" clearable transfer />
      <span style="color: #aaa; margin-left: 10px">(使用单位)</span>
    </div>
    <div v-if="data.pricingType === '1'" class="per-rule">
      <div class="price-row">
        <span><span class="required-star">*</span>计价1：</span>
        <span class="flex items-center">当"穴位/经络/部位" ≤ <a-input placeholder="请输入" class="w-20 ml-2 mr-2" v-model:value="data.cpDynamicPricingRule![0].min" />个时，</span>
        <a-select
          v-model:value="data.cpDynamicPricingRule![0].priceType"
          :options="[
            { label: '单价', value: 0, priceType: 0 },
            { label: '一口价', value: 1, priceType: 1 },
          ]"
          style="width: 100px; margin: 0 4px"
          placeholder="请选择"
        />
        <span>=</span>
        <a-input v-model:value="data.cpDynamicPricingRule![0].price" style="width: 80px; margin: 0 4px" placeholder="请输入" />
        <span>元</span>
      </div>
      <div class="price-row">
        <span><span class="required-star">*</span>计价2：</span>
        <span class="flex items-center"
          >当"穴位/经络/部位" &gt; <a-input placeholder="请输入" class="w-20 ml-2 mr-2" v-model:value="data.cpDynamicPricingRule![1].max" disabled />个时，</span
        >
        <a-select
          v-model:value="data.cpDynamicPricingRule![1].priceType"
          :options="[
            { label: '单价', value: 0, priceType: 0 },
            { label: '一口价', value: 1, priceType: 1 },
          ]"
          style="width: 100px; margin: 0 4px"
          placeholder="请选择"
        />
        <span>=</span>
        <a-input v-model:value="data.cpDynamicPricingRule![1].price" style="width: 80px; margin: 0 4px" placeholder="请输入" />
        <span>元</span>
      </div>

    </div>
    <div class="form-row">
      <label>建议频率：</label>
      <div class="suggested-frequency-row">
        <span>每</span>
        <a-input v-model:value="data.frequencyType" placeholder="请输入" style="width: 100px; margin: 0 8px" />
        <span>天</span>
        <a-input v-model:value="data.frequencyMeasure" placeholder="请输入" style="width: 100px; margin: 0 8px" />
        <vxe-select
          v-model="suggestedFrequencyUnit"
          :options="unitOptions"
          placeholder="请选择"
          :clearable="data.pricingType !== '0'"
          transfer
          style="width: 100px; margin-left: 8px"
        />
      </div>
    </div>
    <div class="form-row" v-if="data.sellType === '2'">
      <label>服务所需时间：</label>
      <a-input v-model:value="data.offlineDuration" placeholder="请输入" style="width: 200px" />
      <span style="margin-left: 8px">分钟</span>
    </div>
    <div class="form-row">
      <label>功效：</label>
      <input v-model="data.effect" style="width: 400px" />
    </div>
    <div class="form-row">
      <label>中药组成：</label>
      <div class="herb-list">
        <template v-for="(herb, idx) in data.cpMedicines || []" :key="idx">
          <div class="herb-item">
            <button class="herb-remove" @click="removeHerb(idx)" type="button">×</button>
            <RemoteSelect :load="cpMedicinesMethod" key-prop="name" v-model:value="herb.name" />
            <a-input v-model:value="herb.dosage" class="herb-dosage" placeholder="剂量" />
            <span>g</span>
          </div>
        </template>
        <button style="margin-left: 8px" @click="addHerb" type="button">+</button>
      </div>
    </div>
    <div class="form-row">
      <label><span class="required-star">*</span>机构名称：</label>
      <a-tree-select
        v-model:value="data.institutionId"
        style="width: 400px"
        :dropdown-style="{ maxHeight: '400px', overflow: 'auto', zIndex: 4000 }"
        placeholder="请选择"
        allow-clear
        tree-default-expand-all
        :tree-data="branch"
        :getPopupContainer="getSafePopupContainer"
        :dropdownMatchSelectWidth="false"
        @change="handleInstitutionChange"
      ></a-tree-select>
    </div>
    <div class="form-row">
      <label>供应商：</label>
      <vxe-select v-model="data.conditioningProgramSupplierId" :options="supplierOptions" placeholder="请选择供应商" style="width: 400px" clearable class="mr-10" />
    </div>
    <div class="form-row">
      <label>图片：</label>
      <a-upload
        :showUploadList="uploadProps"
        v-model:file-list="fileList"
        name="avatar"
        list-type="picture-card"
        class="avatar-uploader"
        @preview="handlePreview"
        :maxCount="1"
        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
        :customRequest="customUpload"
      >
        <div v-if="fileList.length < 1">
          <PlusOutlined />
          <div style="margin-top: 8px">上传</div>
        </div>
      </a-upload>
      <a-image
        :width="200"
        :style="{ display: 'none' }"
        :preview="{
          visible,
          onVisibleChange: setVisible,
        }"
        :src="previewImg"
      />
    </div>
    <div class="form-actions-center">
      <button @click="handleCancel" class="cancel">取消</button>
      <button class="primary" @click="handleOk">确定</button>
    </div>
  </div>
</template>

<style scoped lang="scss">
body,
html,
.form-container {
  overflow-x: hidden !important;
}
.per-rule {
  margin-bottom: 16px;
}
.price-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.suggested-frequency-row {
  display: flex;
  align-items: center;
}
.label {
  font-weight: 500;
  color: #222;
  margin-right: 8px;
  .required-star {
    color: #ff4d4f;
    margin-right: 4px;
  }
}
.form-container {
  position: relative;
  min-height: 500px; /* 根据实际内容调整 */
  padding-bottom: 70px; /* 给底部按钮留空间 */
  margin: 0 auto;
  padding: 32px 0px 32px 30px;
}
.form-row {
  width: 100%;
  overflow: visible;
  display: flex;
  align-items: center;
  margin-bottom: 18px;
  label {
    width: 110px;
    font-weight: 500;
    color: #222;
    .required-star {
      color: #ff4d4f;
      margin-right: 4px;
    }
  }
  input,
  select {
    margin-right: 8px;
    padding: 4px 8px;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
  }
  .herb-list {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }
  .herb-item {
    position: relative;
    display: flex;
    align-items: center;
    margin-right: 8px;
    margin-bottom: 8px;
    padding-left: 16px; /* 给左上角按钮留空间 */
  }
  .herb-name {
    width: 80px;
    padding: 2px 6px;
    font-size: 14px;
  }
  .herb-dosage {
    width: 100px;
    // padding: 2px 6px;
    font-size: 14px;
  }
  .herb-remove {
    position: absolute;
    left: 0;
    top: 0;
    background: #fff;
    border: none;
    color: #ff4d4f;
    font-size: 14px;
    cursor: pointer;
    line-height: 1;
    width: 16px;
    height: 16px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.form-actions-center {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 32px;
}
.primary {
  background: #1890ff;
  color: #fff;
  border: none;
  padding: 0 24px;
  height: 36px;
  border-radius: 4px;
}
.cancel {
  background: #fff;
  color: #222;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  padding: 0 24px;
  height: 36px;
  margin-right: 10px;
}
.required-star {
  color: #ff4d4f;
  margin-right: 4px;
}
</style>
