<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="80vw" @confirm="handleSubmit"
            @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="项目编号" prop="project_num">
                            <el-input v-model="formData.project_num" clearable placeholder="系统自动生成" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目名称" prop="project_name">
                            <el-input v-model="formData.project_name" clearable placeholder="请输入项目名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="关联合同" prop="contract_id">
                            <el-input v-model="formData.contract_name" clearable placeholder="点击选择项目" readonly
                                @click="showDialog = true" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="咨询类型" prop="types">
                            <el-select v-model="formData.types" clearable placeholder="请选择业务性质" class="flex-1">
                                <el-option v-for="(item, index) in dictData.consultation_type" :key="index"
                                    :label="item.name" :value="parseInt(item.value)" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="行业" prop="industry">
                            <el-select v-model="formData.industry" clearable placeholder="请选择行业" class="flex-1"
                                disabled>
                                <el-option v-for="(
                    item, index
                  ) in dictData.cost_consultation_industry_nature" :key="index" :label="item.name"
                                    :value="parseInt(item.value)" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="所在省份" prop="province">
                            <el-select v-model="formData.province" clearable placeholder="请选择省"
                                @change="province_change" class="flex-1">
                                <el-option v-for="(item, index) in datas.provinceOptions" :key="index"
                                    :label="item.province_name" :value="parseInt(item.province_code)" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="所在市区" prop="city">
                            <el-select v-model="formData.city" clearable placeholder="请选择市" class="flex-1">
                                <el-option v-for="(item, index) in datas.cityOptions" :key="index"
                                    :label="item.city_name" :value="parseInt(item.city_code)" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="具体地址" prop="address">
                            <el-input v-model="formData.address" clearable placeholder="请输入具体地址" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="计划开始日期" prop="starting" label-width="120px">
                            <el-date-picker class="flex-1 !flex" v-model="formData.starting" clearable type="date"
                                value-format="YYYY-MM-DD" placeholder="请选择日期" disabled>
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="计划结束日期" prop="endtime" label-width="120px">
                            <el-date-picker class="flex-1 !flex" v-model="formData.endtime" clearable type="date"
                                value-format="YYYY-MM-DD" placeholder="请选择日期" disabled>
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="计划工期" prop="jhgq">
                            <el-input v-model="formData.jhgq" clearable placeholder="请输入计划工期（天）" type="number" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="项目所属部门" prop="depar" :rules="[
                            { required: true, message: '不可为空', trigger: 'blur' },
                        ]">
                            <el-select class="flex-1" v-model="formData.depar" clearable placeholder="请选择部门">
                                <el-option v-for="(item, index) in list2" :key="index" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目负责人" prop="principal">
                            <el-input v-model="formData.principal" clearable placeholder="请输入项目负责人"
                                @click="userclick('principal')" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目相关人员" prop="person" label-width="120px">
                            <el-input v-model="formData.person_text" clearable placeholder="请输入项目相关人员"
                                @click="userclick('person')" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="项目总投资" prop="invest">
                            <el-input v-model="formData.invest" clearable placeholder="请输入项目总投资（元）" type="number"
                                disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="预算造价" prop="budget">
                            <el-input v-model="formData.budget" clearable placeholder="请输入预算造价（元）" type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="送审造价" prop="cost">
                            <el-input v-model="formData.cost" clearable placeholder="请输入送审造价（元）" type="number" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="审定造价" prop="approval">
                            <el-input v-model="formData.approval" clearable placeholder="请输入审定造价（元）" type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="委托单位" prop="aunit">
                            <el-input v-model="formData.aunit" clearable placeholder="请输入委托单位" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="委托方联系人" prop="Acontact" label-width="120px">
                            <el-input v-model="formData.Acontact" clearable placeholder="请输入委托方联系人" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="联系电话" prop="acontactnum">
                            <el-input v-model="formData.acontactnum" clearable placeholder="请输入联系电话" type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="登记日期" prop="date">
                            <el-date-picker class="flex-1 !flex" v-model="formData.date" clearable type="date"
                                value-format="YYYY-MM-DD" placeholder="请选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目规模及概括" prop="generalize" label-width="120px">
                            <el-input v-model="formData.generalize" clearable placeholder="请输入项目规模及概括" disabled
                                type="textarea" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="建设单位" prop="js_unit">
                            <el-input v-model="formData.js_unit" clearable placeholder="请输入建设单位" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="注意事项" prop="note">
                            <el-input v-model="formData.note" clearable placeholder="请输入注意事项" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.remark" clearable placeholder="请输入备注" type="textarea" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-col :span="8">
                    <el-form-item label="附件" prop="annex">
                        <uploadAnnex :formData="formData"></uploadAnnex>
                    </el-form-item>
                </el-col>
                <el-dialog v-model="showDialog" title="选择项目" width="70%">
                    <dialogTable :config="cost_approved_projects" @customEvent="customEvent" :query="{ status: 0 }">
                    </dialogTable>
                </el-dialog>
                <div v-if="showDialog1">
                    <personnelselector ref="personnel" @confirm="submituser" :type="persoleType">
                    </personnelselector>
                </div>
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup name="costProjectEdit">
import type { FormInstance } from "element-plus";
import Popup from "@/components/popup/index.vue";
import { apiCostProjectAdd, apiCostProjectEdit } from "@/api/cost_project";
import { apiCostApprovedProjectDetail } from '@/api/cost_approved_project'
import type { PropType } from "vue";
import { deptAll } from "@/api/org/department";
import { getAll } from "@/api/org/organization";
import { useRoute } from "vue-router";
import { cost_approved_projects } from "@/components/dialogTable/dialogTableConfig";
import { apiCityList, apiProvinceList } from "@/api/common";
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({}),
    },
});
const emit = defineEmits(["success", "close"]);
const formRef = shallowRef<FormInstance>();
const popupRef = shallowRef<InstanceType<typeof Popup>>();
const mode = ref("add");
const showDialog = ref(false);
const showDialog1 = ref(false);
const list1 = reactive([]);
const list2 = reactive([]);
const personnel = ref<any>();
const route = useRoute();

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == "edit" ? "编辑造价项目台账" : "新增造价项目台账";
});

// 表单数据
const formData = reactive({
    id: "",
    project_num: "",
    project_name: "",
    contract_id: "",
    contract_name: "",
    types: "",
    industry: "",
    province: "",
    city: "",
    org_id: "",
    js_unit: "",
    address: "",
    starting: "",
    endtime: "",
    jhgq: "",
    depar: "",
    principal: "",
    principal_id: "",
    person: "",
    person_text: "",
    invest: "",
    budget: "",
    cost: "",
    approval: "",
    aunit: "",
    Acontact: "",
    acontactnum: "",
    date: "",
    generalize: "",
    note: "",
    remark: "",
    annex: [],
});
//获取所有组织
const getlist = () => {
    getAll().then((res) => {
        Object.assign(list1, res);
    });
};
//获取部门
const deptrmt = (e: any) => {
    formData.dept_id = "";
    getlist1(e);
};
//获取所有部门
const getlist1 = (id: any) => {
    deptAll({ org_id: id }).then((res) => {
        list2.splice(0, list2.length, ...res);
    });
};

const datas = reactive({
    provinceOptions: [],
    cityOptions: [],
});

const customEvent = (e) => {
    formData.contract_id = e.id;
    formData.contract_name = e.contract_name;
    formData.industry = e.industry_nature
    formData.starting = e.start_date
    formData.endtime = e.end_date
    formData.principal = e.project_director
    formData.invest = e.project_money
    formData.aunit = e.part_a
    formData.generalize = e.project_scale
    formData.Acontact = e.part_a_contract
    showDialog.value = false;
};

const getProvinceList = async () => {
    const data = await apiProvinceList({});
    datas["provinceOptions"] = data;
};
const getCityList = async () => {
    const data = await apiCityList({ province_code: formData.province });
    datas["cityOptions"] = data;
};

//获取省份
function province_change(value: string) {
    getCityList();
}


const chekcDate = (rule: any, value: any, callback: any) => {
    if (new Date(formData.date) < new Date(formData.starting)) {
        callback(new Error('登记日期不能早于计划开始日期'))
    } else {
        callback()
    }
}

// 表单验证
const formRules = reactive<any>({
    project_name: [
        {
            required: true,
            message: "请输入项目名称",
            trigger: ["blur"],
        },
    ],
    contract_id: [
        {
            required: true,
            message: "请输入关联合同",
            trigger: ["blur"],
        },
    ],
    starting: [
        {
            required: true,
            message: "请输入计划开始日期",
            trigger: ["blur"],
        },
    ],
    endtime: [
        {
            required: true,
            message: "请输入计划结束日期",
            trigger: ["blur"],
        },
    ],
    date: [{
        required: true,
        message: '请输入登记日期',
        trigger: ['blur']
    },
    {
        validator: chekcDate,
        trigger: ['blur']
    }],
    jhgq: [
        {
            required: true,
            message: "请输入计划工期（天）",
            trigger: ["blur"],
        },
    ],
    principal: [
        {
            required: true,
            message: "请输入项目负责人",
            trigger: ["blur"],
        },
    ],
    invest: [
        {
            required: true,
            message: "请输入项目总投资（元）",
            trigger: ["blur"],
        },
    ],
    aunit: [
        {
            required: true,
            message: "请输入委托单位",
            trigger: ["blur"],
        },
    ],
});

// 获取详情
const setFormData = async (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key];
        }
    }
    formData.province = Number(formData.province);
    formData.city = Number(formData.city);
    formData.depar = Number(formData.depar);
    formData.contract_name = data.contract.contract_name;
    formData.principal = data.contract?.signing_person
    formData.starting = data.contract.start_date
    formData.endtime = data.contract.end_date
    getCityList();
    deptrmt(formData.org_id);
};

// 提交按钮
const handleSubmit = async () => {
    Array.isArray(formData.annex) ? "" : (formData.annex = []);
    await formRef.value?.validate();
    const data = { ...formData };
    mode.value == "edit"
        ? await apiCostProjectEdit(data)
        : await apiCostProjectAdd(data);
    popupRef.value?.close();
    emit("success");
};

//打开弹窗
const open = (type = "add") => {
    mode.value = type;
    popupRef.value?.open();
    getlist();
};
//打开弹窗
const userclick = async (e: any) => {
    e == "person" ? (persoleType.value = 2) : (persoleType.value = 1);
    // label.value = e
    showDialog1.value = true;
    await nextTick();
    personnel.value.open();
};

const persoleType = ref("1");
//确认
const submituser = (e: any) => {
    let flag = Array.isArray(e);
    let personl;
    let personl_id;
    personl = flag ? e.map((item) => [item.name]).join(",") : e.name;
    personl_id = flag ? e.map((item) => item.id) : e.id;
    if (flag) {
        formData.person_text = personl;
        formData.person = personl_id;
    } else {
        formData.principal = personl;
        formData.principal_id = personl_id;
    }
    showDialog1.value = false;
};

// 关闭回调
const handleClose = () => {
    emit("close");
};

if (route.query.contractId) {
    // handleAdd()
    apiCostApprovedProjectDetail({ id: route.query.contractId }).then(res => {
        customEvent(res)
    })
    // // handleAdd()
    // formData.contract_id = route.query.contractId;
    // formData.contract_name = route.query.contractName;
}

getProvinceList();

defineExpose({
    open,
    setFormData,
});
</script>
