<script lang="ts" setup>
import { ref, watch } from 'vue';
import { Form, message } from 'ant-design-vue';
import VxeUI from 'vxe-table';
import { useRequest } from 'alova/client';
import { getDictionaryMethod, cpMedicinesMethod } from '@/request/api/dictionary.api';
import { branchMethod } from '@/request/api/system.api';
import { systemCpEditMethod, getAllSupplierMethod, getConditioningSchemeDetailMethod } from '@/request/api/care.api';
import { UploadIFile } from '@/request/api/follow.api';
import type { SystemItemModel } from '@/model/care.model';
import RemoteSelect from '@/libs/v-select-page/RemoteSelect.vue';
import type { UploadFile } from 'ant-design-vue/es/upload/interface';
import type { FormInstance } from 'ant-design-vue';
type SystemModel = Partial<SystemItemModel>;
const props = defineProps<{ data: SystemModel; title: string }>();
const formRef = ref<FormInstance>();
const typeOptions = ref<{ label: string; value: string }[]>([]);

const supplierOptions = ref<{ label: string; value: string }[]>([]);
const branchOptions = ref<{ label: string; value: string }[]>([]);

const unitOptions = [
  { label: '袋', value: '袋' },
  { label: '包', value: '包' },
  { label: '贴', value: '贴' },
  { label: '次', value: '次' },
];

// 获取所有的机构
const { data: branch, loading: branchLoading } = useRequest(branchMethod).onSuccess(({ data }) => {
  if (data?.length > 0) {
    branchOptions.value = data.map((item: any) => ({
      label: item.label,
      value: item.id,
    }));
  }
});

const form = reactive<SystemModel>({
  conditioningProgramType: '',
  conditioningProgramSupplierId: '',
  institutionId: '',
  cpDynamicPricingRule: [
    { min: 0, max: 0, priceType: 0, price: 0 },
    { min: 0, max: 0, priceType: 0, price: 0 },
  ],
  pricingType: '0',
  cpFixedPricingRule: {
    unitPrice: 0,
    pricingUnit: '',
    convertDose: 0,
    convertUnit: '',
  },
  cpMedicines: [{ name: '', dosage: '', id: '' }],
  isOnline: '',
  isDelivery: '',
});
const onlineArr = ref<string[]>([]);
const deliverArr = ref<string[]>([]);
const rules = {
  name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  conditioningProgramType: [{ required: true, message: '请选择方案类型', trigger: 'change' }],
  pricingType: [{ required: true, message: '请选择计价规则', trigger: 'change' }],
  conditioningProgramSupplierId: [{ required: true, message: '请选择供应商', trigger: 'change' }],
  institutionId: [{ required: true, message: '请选择机构名称', trigger: 'change' }],
  // isOnline: [{ required: true, message: '请选择线上项目', trigger: 'change' }],
};
const isShowOnline = ref<boolean>(false);
const isShowDelivery = ref<boolean>(false);
const supplierArr = ref<any[]>([]);


// 获取所有的供应商
async function getSupplier(params: any) {
  const res = await getAllSupplierMethod(params);
  if (res && res.length > 0) {
    supplierArr.value = res;
    supplierOptions.value = res.map((item: any) => ({
      label: item.name,
      value: item.id,
    }));
    getIsOnline(params.conditioningProgramSupplierId, params.isOnline, params.isDelivery, params.conditioningProgramTypes);
  }
}
function getIsOnline(e: any, newOnline: any, newDelivery: any, newType: any) {
  let filterSupplierArr = supplierArr.value.filter((item: any) => item.id === e);
  if (filterSupplierArr.length > 0) {
    isShowOnline.value = filterSupplierArr.every((items: any) => {
      if (newType.length > 0) {
        return items.offlineCPTypes.includes(newType[0]) && items.onlineCPTypes.includes(newType[0]);
      } else {
        return false;
      }
    });
    if (isShowOnline.value) {
      if (newOnline) {
        onlineArr.value = [newOnline];
        if (onlineArr.value.length > 1) {
          onlineArr.value = [onlineArr.value[onlineArr.value.length - 1]];
        } else if (onlineArr.value.length === 0) {
          onlineArr.value = [];
        }

        if (newOnline === 'Y') {
          isShowDelivery.value = true;
        } else {
          form.isDelivery = '';
          isShowDelivery.value = false;
        }
      }
      if (newDelivery) {
        deliverArr.value = [newDelivery];
        if (deliverArr.value.length > 1) {
          deliverArr.value = [deliverArr.value[deliverArr.value.length - 1]];
        } else if (deliverArr.value.length === 0) {
          deliverArr.value = [];
        }
      }
    }
  }else{
    isShowOnline.value = false;
    isShowDelivery.value = false;
    onlineArr.value = [];
    deliverArr.value = [];
  }
}
watch(
  [() => form.conditioningProgramType, () => form.institutionId, () => form.conditioningProgramSupplierId, () => form.isOnline, () => form.isDelivery],
  ([newType, newInstitutionId, newSupplierId, newOnline, newDelivery]) => {
    getSupplier({
      conditioningProgramTypes: newType ? [newType] : form.conditioningProgramType ? [form.conditioningProgramType] : [],
      institutionId: newInstitutionId ? newInstitutionId : form.institutionId ? form.institutionId : '',
      conditioningProgramSupplierId: newSupplierId ? newSupplierId : form.conditioningProgramSupplierId ? form.conditioningProgramSupplierId : '',
      isOnline: newOnline,
      isDelivery: newDelivery,
    });
  },
  { immediate: true }
);

function addHerb() {
  if (!form.cpMedicines) {
    form.cpMedicines = [];
  }
  form.cpMedicines.push({ name: '', dosage: '', id: '' });
}
function removeHerb(idx: number) {
  if (form.cpMedicines) {
    form.cpMedicines.splice(idx, 1);
  }
}
function cancel() {
  VxeUI.modal.close(`add-items-modal`);
}
function doSubmit() {
  console.log(formRef.value, 'formRef==>');
  console.log(form, 'Form Data Before Submit');
  formRef.value
    ?.validate()
    .then((res) => {
      console.log(res, 'res==>111');
      form.photo = fileList.value[0]?.response?.url || '';
      submit(form);
    })
    .catch((error) => {
      console.error('Validation Error:', error);
      message.error('请完善必填项');
    });
}
// 获取方案类型
async function getConditioningProgramType() {
  try {
    const res = await getDictionaryMethod('condition_type');
    if (res?.length > 0) {
      typeOptions.value = res; // 直接使用返回的数据
    }
  } catch (error) {
    console.error('获取方案类型列表失败:', error);
  }
}

onMounted(async () => {
  const deptId = localStorage.getItem('deptId');
  if (form.addType === 'system' && deptId) {
    form.institutionId = deptId;
  }
  form.addType = props.data.addType;
  if (props.data.id) {
    const res: any = await getConditioningSchemeDetailMethod(props.data);
    Object.assign(form, res);
    form.cpMedicines = (res.cpMedicines ?? []).map((item: any) => ({
      name: item.name || item.herbName || item.medicineName || '',
      dosage: item.dosage,
      id: item.id,
    }));

    fileList.value = res.photo
      ? [
          {
            uid: '-1',
            name: 'image.png',
            status: 'done',
            url: res.photo,
            thumbUrl: res.photo,
          },
        ]
      : [];
  }
  // 获取供应商
  // getSupplier({});
  // 获取方案类型
  getConditioningProgramType();
});
const emits = defineEmits<{
  submit: [data?: SystemItemModel];
  addSubmit: [data?: SystemItemModel];
}>();
const { loading: submitting, send: submit } = useRequest(systemCpEditMethod, {
  immediate: false,
}).onSuccess(({ data }) => {
  emits('submit');
});

const visible = ref<boolean>(false);
const setVisible = (value): void => {
  visible.value = value;
};
const previewImg = ref<string>('');
const uploadProps = reactive({ showRemoveIcon: true });
const fileList = ref<UploadFile[]>([]);
// 预览图片
const handlePreview = async (file: UploadFile) => {
  previewImg.value = file.response?.url ?? file.thumbUrl;
  visible.value = true;
};

function customUpload(e: any) {
  // uploadApi 你的二次封装上传接口
  UploadIFile(e.file)
    .then((res) => {
      // 调用实例的成功方法通知组件该文件上传成功
      e.onSuccess(res, e);
    })
    .catch((err) => {
      // 调用实例的失败方法通知组件该文件上传失败
      e.onError(err);
    });
}

watch(
  () => form.pricingType,
  (val) => {
    if (val === '0' && !form.cpFixedPricingRule) {
      form.cpFixedPricingRule = {
        unitPrice: 0,
        pricingUnit: '',
        convertDose: 0,
        convertUnit: '',
      };
    } else {
      form.cpFixedPricingRule = null;
    }
  }
);
function bindchange(e: any) {
  form.conditioningProgramSupplierId = '';
  form.isOnline = '';

}
function onlineChange(value: any) {
  form.isOnline = value[value.length - 1];
  deliverArr.value = [];
  form.isDelivery = '';
}
function deliveryChange(value: any) {
  form.isDelivery = value[value.length - 1];
}
function getConditioningProgramSupplier(value: any) {
  onlineArr.value = [];
  deliverArr.value = [];
  form.isOnline = '';
  form.isDelivery = '';
  isShowDelivery.value = false;
}
</script>

<template>
  <div class="form-container">
    <a-form ref="formRef" :model="form" :rules="rules" layout="horizontal">
      <a-form-item label="项目名称：" name="name" required>
        <a-input v-model:value="form.name" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="方案类型：" name="conditioningProgramType" required>
        <a-select v-model:value="form.conditioningProgramType" :options="typeOptions" placeholder="请选择" allowClear @change="bindchange" />
      </a-form-item>
      <a-form-item label="计价规则：" name="pricingType" required>
        <a-radio-group v-model:value="form.pricingType">
          <a-radio value="0">一口价</a-radio>
          <a-radio value="1">按穴位/经络/部位</a-radio>
        </a-radio-group>
      </a-form-item>
      <div class="price-row" v-if="form.pricingType === '0' && form.cpFixedPricingRule">
        <span class="label">单价：</span>
        <a-input v-model:value="form.cpFixedPricingRule.unitPrice" placeholder="请输入" style="width: 100px" />
        <span style="margin: 0 8px">元</span>

        <span class="label" style="margin-left: 32px">计价单位：</span>
        <a-input v-model:value="form.cpFixedPricingRule.pricingUnit" placeholder="请输入" style="width: 100px" />

        <span style="margin-left: 32px">相当于</span>
        <a-input v-model:value="form.cpFixedPricingRule.convertDose" placeholder="请输入" style="width: 100px; margin-left: 8px" />
        <a-select v-model:value="form.cpFixedPricingRule.convertUnit" style="width: 100px; margin-left: 8px" :options="unitOptions" placeholder="请选择" />

        <span style="color: #aaa; margin-left: 8px">(使用单位)</span>
      </div>
      <div v-if="form.pricingType === '1'" class="per-rule">
        <div class="price-row">
          <span>计价1：</span>
          <span class="flex items-center"
            >当"穴位/经络/部位" ≤
            <a-input
              placeholder="请输入"
              class="w-20 ml-2 mr-2"
              v-model:value="form.cpDynamicPricingRule[0].min"
              @change="() => (form.cpDynamicPricingRule[1].max = form.cpDynamicPricingRule[0].min)"
            />个时，</span
          >
          <a-select
            v-model:value="form.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="form.cpDynamicPricingRule[0].price" style="width: 80px; margin: 0 4px" placeholder="请输入" />
          <span>元</span>
        </div>
        <div class="price-row">
          <span>计价2：</span>
          <span class="flex items-center"
            >当"穴位/经络/部位" &gt; <a-input placeholder="请输入" class="w-20 ml-2 mr-2" v-model:value="form.cpDynamicPricingRule[1].max" disabled />个时，</span
          >
          <a-select
            v-model:value="form.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="form.cpDynamicPricingRule[1].price" style="width: 80px; margin: 0 4px" placeholder="请输入" />
          <span>元</span>
        </div>
      </div>

      <a-form-item label="中药组成：">
        <div class="herb-list">
          <template v-for="(herb, idx) in form.cpMedicines" :key="herb.id">
            <div class="herb-item">
              <button class="herb-remove" v-if="form?.cpMedicines?.length > 1" @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>
      </a-form-item>
      <a-form-item label="功效：">
        <a-input v-model:value="form.effect" placeholder="请输入" />
      </a-form-item>
      <!-- 机构名称 -->
      <a-form-item label="机构名称：" v-if="form?.addType === 'itemsList'" required name="institutionId">
        <a-select v-model:value="form.institutionId" :options="branchOptions" placeholder="请选择" allowClear />
      </a-form-item>
      <a-form-item label="供应商：" required name="conditioningProgramSupplierId">
        <a-select v-model:value="form.conditioningProgramSupplierId" :options="supplierOptions" placeholder="请选择" allowClear @change="getConditioningProgramSupplier" />
      </a-form-item>
      <a-form-item label="线上项目：" name="isOnline" v-if="isShowOnline" required>
        <a-checkbox-group v-model:value="onlineArr" @change="onlineChange">
          <a-checkbox value="Y">是</a-checkbox>
          <a-checkbox value="N">否</a-checkbox>
        </a-checkbox-group>
      </a-form-item>
      <a-form-item label="配送：" name="isDelivery" v-if="isShowDelivery">
        <a-checkbox-group v-model:value="deliverArr" @change="deliveryChange">
          <a-checkbox value="Y">支持</a-checkbox>
          <a-checkbox value="N">不支持</a-checkbox>
        </a-checkbox-group>
      </a-form-item>
      <a-form-item label="图片：">
        <a-upload :showUploadList="uploadProps" v-model:file-list="fileList" list-type="picture-card" @preview="handlePreview" :maxCount="1" :customRequest="customUpload">
          <div v-if="fileList.length < 1">
            <plus-outlined />
            <div style="margin-top: 8px">上传</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-image
        :width="200"
        :style="{ display: 'none' }"
        :preview="{
          visible,
          onVisibleChange: setVisible,
        }"
        :src="previewImg"
      />
      <div class="form-actions-center">
        <a-button @click="cancel">取消</a-button>
        <a-button type="primary" style="background: #faad14; border: none" @click="doSubmit">确定</a-button>
      </div>
    </a-form>
  </div>
</template>

<style scoped>
.form-container {
  width: 760px;
  margin: 0 auto;
  padding: 10px 0px 0 0;
}
.per-rule {
  margin-bottom: 16px;
}
.price-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.label {
  font-weight: 500;
  color: #222;
  margin-right: 8px;
}
.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-dosage {
  width: 70px;
  padding: 2px 6px;
  font-size: 14px;
  margin-right: 10px;
}
.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; */
}
.slider-section {
  margin-bottom: 16px;
}
.slider-labels {
  display: flex;
  justify-content: space-between;
  width: 200px;
  margin-left: 230px;
  margin-bottom: 4px;
  font-weight: 500;
  color: #222;
}
.slider-row {
  display: flex;
  align-items: center;
}
.slider-desc {
  color: #222;
  white-space: nowrap;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.slider-value {
  margin-left: 16px;
  color: #faad14;
  font-weight: bold;
}
</style>
