<template>
  <ContentWrap class="mt-10px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="140px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="商机名称" prop="name">
            <el-input v-model="formData.name" :disabled="type" clearable placeholder="请输入商机名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="线索拓展人" prop="ownerUserId">
            <el-select
              v-model="formData.ownerUserId"
              disabled
              placeholder="请选择线索拓展人"
              class="w-1/1"
            >
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="需求提交人" prop="requestorUserId">
            <el-select
              v-model="formData.requestorUserId"
              clearable
              
              :disabled="formType || type"
              :placeholder="formType ? '' : '请选择需求提交人'"
              class="w-1/1"
            >
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户名称" prop="customerId">
            <el-select
              :disabled="formData.customerDefault || type"
              v-model="formData.customerId"
              clearable
              filterable
              placeholder="请选择客户"
              class="w-1/1"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="归属部门" prop="deptId">
            <el-tree-select
              v-model="formData.deptId"
              :data="deptTree"
               :disabled="type"
              :props="defaultProps"
              filterable
              clearable
              check-strictly
              node-key="id"
              :placeholder="type ? '' : '请选择归属部门'"
            />
          </el-form-item>
      </el-col>
        <el-col :span="8">
          <el-form-item label="商机状态组" prop="statusTypeId">
            <el-select
              v-model="formData.statusTypeId"
              placeholder="请选择商机状态组"
              clearable
              class="w-1/1"
              :disabled="formType || type"
            >
              <el-option
                v-for="item in statusTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="预计成交日期" prop="dealTime">
            <el-date-picker
              v-model="formData.dealTime"
              type="date"
              :disabled="type"
              value-format="x"
              :placeholder="type ? '' : '请选择预计成交日期'"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="销售阶段" prop="saleStage">
            <el-select v-model="formData.saleStage" :disabled="type" clearable placeholder="请选择销售阶段">
              <el-option
                v-for="dict in getIntDictOptions('sale_stage')"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="8">
          <el-form-item label="授信方式" prop="creditMethod">
            <el-select v-model="formData.creditMethod" :disabled="type" clearable placeholder="请选择授信方式">
              <el-option
                v-for="dict in getIntDictOptions('credit_method')"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="账期" prop="paymentTerm">
            <el-select v-model="formData.paymentTerm" :disabled="type" @change="changePayment" clearable placeholder="请选择账期">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PAYMENT_TERM)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="授信计算周期" prop="creditCalcCycle">
            <!-- <el-select v-model="formData.creditCalcCycle" placeholder="请选择授信计算周期">
              <el-option
                v-for="dict in getIntDictOptions('credit_calc_cycle')"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select> -->
            <el-input v-model="formData.creditCalcCycle" disabled placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="授信额度" prop="creditLimit">
            <el-input v-model="formData.creditLimit" disabled placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="技术需求支持" prop="techSupport">
            <el-radio-group v-model="formData.techSupport" :disabled="type">
              <el-radio
                v-for="dict in getStrDictOptions(DICT_TYPE.TECH_SUPPORT)"
                :key="dict.value"
                :value="dict.value == 2 ? true : false"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" :disabled="type" v-model="formData.remark" clearable :placeholder="formType ? '' : '请输入备注'" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 子表的表单 -->
      <ContentWrap>
        <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
          <el-tab-pane label="产品清单" name="product">
            <BusinessProductForm
              ref="productFormRef"
              :products="formData.products"
              :disabled="type"
              @success="setList"
            />
          </el-tab-pane>
        </el-tabs>
      </ContentWrap>
      <el-row>
        <el-col :span="8">
          <el-form-item label="线上总金额（元）" prop="onlinePrice">
            <el-input
              disabled
              v-model="formData.onlinePrice"
              :formatter="erpPriceInputFormatter"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="线下总金额（元）" prop="offlinePrice">
            <el-input
              disabled
              v-model="formData.offlinePrice"
              :formatter="erpPriceInputFormatter"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="总金额（元）" prop="totalPrice">
            <el-input
              disabled
              v-model="formData.totalPrice"
              :formatter="erpPriceInputFormatter"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
      <div style="text-align: right" v-if="!type">
        <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
        <el-button @click="goBack">取 消</el-button>
    </div>
  </ContentWrap>

</template>
<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { getIntDictOptions, getStrDictOptions, DICT_TYPE, getBoolDictOptions } from '@/utils/dict';
import * as BusinessApi from '@/api/crm/business';
import * as BusinessStatusApi from '@/api/crm/business/status';
import * as CustomerApi from '@/api/crm/customer';
import * as UserApi from '@/api/system/user';
import * as DeptApi from '@/api/system/dept';
import { useUserStore } from '@/store/modules/user';
import { defaultProps, handleTree } from '@/utils/tree';
import BusinessProductForm from './components/BusinessProductForm.vue';
import { erpPriceMultiply, erpPriceInputFormatter } from '@/utils';
import { propTypes } from '@/utils/propTypes'

const { proxy }: any = getCurrentInstance();
const { t } = useI18n();
const message = useMessage();

const dialogVisible = ref(false);
const dialogTitle = ref('');
const formLoading = ref(false);
const formType = ref('');
const formData = ref({
  id: undefined,
  name: undefined,
  customerId: undefined,
  followUpStatus: undefined,
  contactLastTime: undefined,
  contactNextTime: undefined,
  ownerUserId: undefined,
  deptId: undefined,
  requestorUserId: undefined,
  statusTypeId: undefined,
  statusId: undefined,
  endStatus: undefined,
  dealTime: undefined,
  onlinePrice: 0,
  offlinePrice: 0,
  totalProductPrice: 0,
  totalPrice: 0,
  saleStage: undefined,
  paymentTerm: undefined,
  creditMethod: undefined,
  creditCalcCycle: undefined,
  creditLimit: undefined,
  techSupport: false,
  products: []
});
const formRules = reactive({
  name: [{ required: true, message: '商机名称不能为空', trigger: 'blur' }],
  customerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
  ownerUserId: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
  statusTypeId: [{ required: true, message: '商机状态组不能为空', trigger: 'blur' }],
  saleStage: [{ required: true, message: '销售阶段不能为空', trigger: 'change' }],
  paymentTerm: [{ required: true, message: '账期不能为空', trigger: 'change' }],
  creditMethod: [{ required: true, message: '授信方式不能为空', trigger: 'change' }],
  techSupport: [{ required: true, message: '技术需求支持不能为空', trigger: 'change' }],

});
const formRef = ref();
const userOptions = ref<UserApi.UserVO[]>([]);
const statusTypeList = ref([]);
const customerList = ref([]);
const deptTree = ref();
const props = defineProps({
  type: propTypes.number.def(undefined)
})
const subTabsName = ref('product');
const productFormRef = ref();

watch(
  () => formData.value.products,
  (newProducts) => {
    if (!Array.isArray(newProducts)) {
      console.warn('formData.value.products is not an array');
      return;
    }

    let totalOnlinePrice = 0;
    let totalOfflinePrice = 0;

    for (const product of newProducts) {
      if (typeof product.onlinePrice) {
        totalOnlinePrice += Number(product.onlinePrice);
      }
      if (typeof product.offlinePrice) {
        totalOfflinePrice += Number(product.offlinePrice);
      }
    }
    formData.value.onlinePrice = totalOnlinePrice.toFixed(2) 
    formData.value.offlinePrice = totalOfflinePrice.toFixed(2) 
    let all =  totalOnlinePrice + totalOfflinePrice
    formData.value.totalPrice = all.toFixed(2)
  },
  { deep: true }
);

watch(
  () => formData.value.totalPrice,
  (newProducts) => {
    formData.value.creditLimit = parseInt(newProducts / 365 * formData.value.creditCalcCycle) || ''

  },
  { deep: true }
);

const open = async (id?: number, customerId?: number) => {
  if (id) {
    formLoading.value = true;
    try {
      const data = await BusinessApi.getBusiness(id);
      formData.value = {
        ...data,
        products: data.products || []
      };
    } finally {
      formLoading.value = false;
    }
  } else {
    if (customerId) {
      formData.value.customerId = customerId;
      formData.value.customerDefault = true;
    }
  }

};

const setList = (newProducts) => {
  formData.value.products = newProducts;
};

// 改版账期
const changePayment = (val) => {

const currentDate = new Date(); // 获取当前日期
const currentMonth = currentDate.getMonth() + 1; // 获取当前月份（注意月份是从0开始的，所以需要加1）
const daysInMonth = new Date(currentDate.getFullYear(), currentMonth, 0).getDate(); // 获取指定月份的天数
 formData.value.creditCalcCycle = (val > 2 ? parseInt(daysInMonth + Number(val)) : 0)
 formData.value.creditLimit = parseInt(formData.value.totalPrice / 365 * formData.value.creditCalcCycle)
}
const { push } = useRouter()

const submitForm = async () => {
  const productFormRef1 = await productFormRef.value.validate();
  if (!productFormRef1) return;
  const valid = await formRef.value.validate();
  if (!valid) return;


  formLoading.value = true;
  try {
    const data = formData.value as unknown as BusinessApi.BusinessVO;
    if (!formType.value) {
      await BusinessApi.createBusiness(data);
      message.success(t('common.createSuccess'));

    } else {
      await BusinessApi.updateBusiness(data);
      message.success(t('common.updateSuccess'));
    }
    dialogVisible.value = false;
    goBack()

  } finally {
    formLoading.value = false;
  }
};

const goBack = ()=> {
  proxy.$router.go(-1)
}
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    customerId: undefined,
    ownerUserId: undefined,
    statusTypeId: undefined,
    dealTime: undefined,
    totalPrice: 0,
    products: [],
    contactId: undefined,
    techSupport: 1,
    customerDefault: false
  };
  formRef.value?.resetFields();
};

const route = useRoute();
onMounted(async () => {
  const customerId = route.query.customerId;
  formData.value.ownerUserId = customerId ? '' : useUserStore().getUser.id;
  formType.value = route.query.id || route.params.id;
  if (formType.value) open(formType.value, customerId)
  customerList.value = await CustomerApi.getSelfCustomerSimpleList();
  statusTypeList.value = await BusinessStatusApi.getBusinessStatusTypeSimpleList();
  userOptions.value = await UserApi.getSimpleUserList();
  deptTree.value = handleTree(await DeptApi.getSimpleDeptList());
});
</script>
