<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="650px" @confirm="handleSubmit" @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules">
                <el-form-item label="组织id" prop="org_id" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                    <el-select class="flex-1" v-model="formData.org_id" clearable placeholder="请选择组织id"
                        @change="area_change">
                        <el-option v-for="(item, index) in orglist" :key="index" :label="item.name"
                            :value="parseInt(item.id)" />
                    </el-select>
                </el-form-item>
                <el-form-item label="部门id" prop="dept_id" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                    <el-select class="flex-1" v-model="formData.dept_id" clearable placeholder="请选择部门id">
                        <el-option v-for="(item, index) in jobs" :key="index" :label="item.name"
                            :value="parseInt(item.id)" />
                    </el-select>
                </el-form-item>
                <el-form-item label="项目名称" prop="project_id" @click="showDialog = true"
                    :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                    <el-input v-model="project_name" clearable readonly placeholder="请输入项目名称" />
                </el-form-item>
                <el-form-item label="项目编码" prop="project_id">
                    <el-input v-model="project_code" disabled clearable placeholder="系统自动填写" />
                </el-form-item>
                <el-form-item label="客户名称" prop="project_id">
                    <el-input v-model="custom_name" disabled clearable placeholder="系统自动填写" />
                </el-form-item>
                <el-form-item label="需求名称" prop="customer_demand_id">
                    <el-input v-model="customer_demand_name" clearable readonly placeholder="选择需求" @click="xuDialog" />
                </el-form-item>
                <el-form-item label="竞争对手名称" prop="competitor_name">
                    <el-input v-model="formData.competitor_name" clearable placeholder="请输入竞争对手名称"
                        :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]" />
                </el-form-item>
                <el-form-item label="竞争对手联系人" prop="competitor_contacts">
                    <el-input v-model="formData.competitor_contacts" clearable placeholder="请输入竞争对手联系人"
                        :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]" />
                </el-form-item>
                <el-form-item label="联系人电话" prop="competitor_contacts_phone"
                    :rules="[{ validator: checkPhone, trigger: 'blur' }]">
                    <el-input v-model="formData.competitor_contacts_phone" clearable placeholder="请输入联系人电话" />
                </el-form-item>

                <el-form-item label="竞争能力" prop="competitive_power">
                    <el-input v-model="formData.competitive_power" clearable placeholder="请输入竞争能力" />
                </el-form-item>
                <el-form-item label="竞争对手优势" prop="competitor_advantages">
                    <el-input v-model="formData.competitor_advantages" clearable placeholder="请输入竞争对手优势" />
                </el-form-item>
                <el-form-item label="竞争对手劣势" prop="competitor_disadvantages">
                    <el-input v-model="formData.competitor_disadvantages" clearable placeholder="请输入竞争对手劣势" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="formData.remark" clearable placeholder="请输入备注" />
                </el-form-item>
                <el-form-item label="附件" prop="field127">
                    <el-upload
                        accept="doc, docx, xls, xlsx, ppt, pptx, pdf, txt, zip, rar, tar, jpg, png, gif, jpeg, webp, wmv, avi, mpg, mpeg, 3gp, mov, mp4, flv, f4v, rmvb, mkv"
                        class="upload-demo" :show-file-list="false" aria-hidden="true" :headers="{ Token: userStore.token }"
                        :action="base_url + '/upload/file'" :on-success="handleAvatarSuccess_four" ref="upload">
                        <el-button type="primary">
                            上传
                        </el-button>
                    </el-upload>
                    <div>
                        <div v-for="(item, index) in formDataannex" style="margin-left: 5px;display: block;">
                            <a style="margin-left: 10px; color: #4a5dff; align-self: flex-start" :href="item.uri"
                                target="_blank">{{ item.name }}</a>
                            <span style="cursor: pointer;margin-left: 5px;" @click="delFileFn(index)">x</span>
                        </div>
                    </div>
                </el-form-item>
            </el-form>
        </popup>
        <el-dialog v-model="showDialog" title="选择项目" width="70%">
            <projectTable @customEvent="customEvent"></projectTable>
        </el-dialog>
        <div v-if="showDialog1">
            <el-dialog v-model="showDialog1" title="选择需求" width="70%">
                <customerdemand @customEvent="customEvent1" :productid="formData.project_id"></customerdemand>
            </el-dialog>
        </div>
    </div>
</template>

<script lang="ts" setup name="competitorEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiCompetitorAdd, apiCompetitorEdit, apiCompetitorDetail } from '@/api/competitor'
import { timeFormat } from '@/utils/util'
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import projectTable from "@/components/project/index.vue"
import customerdemand from "@/components/customerdemand/index.vue"
import type { PropType } from 'vue'
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 orglist = reactive([])
const jobs = reactive([])
const project_name
    = ref('')
const project_code
    = ref('')
const custom_name
    = ref('')
const customer_demand_name = ref('')
const formDataannex = reactive([])
import configs from "@/config"
const base_url = configs.baseUrl + configs.urlPrefix
import useUserStore from "@/stores/modules/user";
import feedback from '@/utils/feedback'

const userStore = useUserStore();
// 上传文件
const handleAvatarSuccess_four = (
    response,
    uploadFile
) => {
    if (response.code == 0) {
        ElMessage.error(response.msg);
        return;
    }
    formDataannex.push(
        { uri: response.data.uri, name: response.data.name }

    );
};
// 删除上传的文件
const delFileFn = (index: number) => {
    formDataannex.splice(index, 1)
}
// dialog
const showDialog = ref(false)
const showDialog1 = ref(false)
//获取弹窗选择的值
const customEvent = (e: any) => {
    formData.project_id = e.id;
    project_name.value = e.name;
    project_code
        .value = e.project_code;
    custom_name
        .value = e.custom_name;
    showDialog.value = false;
};
const customEvent1 = (e: any) => {
    formData.customer_demand_id = e.id;
    customer_demand_name.value = e.theme;

    showDialog1.value = false;
};
const getlista = () => {
    getAll().then((res) => {
        // orglist = res.data

        Object.assign(orglist, res)

    })
}

const area_change = (e: any) => {
    formData.org_id = e
    let data = { 'org_id': e }
    // console.log(data)
    deptAll(data).then((res) => {
        Object.assign(jobs, res)
    })
}
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑竞争对手' : '新增竞争对手'
})
//打开需求弹窗
const xuDialog = () => {
    if (formData.project_id) {
        showDialog1.value = true
    } else {
        feedback.msgError('请先选择项目')
    }
}
// 表单数据
const formData = reactive({
    id: '',
    org_id: '',
    dept_id: '',
    project_id: '',
    customer_demand_id: '',
    competitor_name: '',
    competitor_contacts: '',
    competitor_contacts_phone: '',
    competitive_power: '',
    competitor_advantages: '',
    competitor_disadvantages: '',
    remark: '',
    annex: [],
})

const checkPhone = (rule: any, value: any, callback: (arg0: Error) => any) => {
    const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/

    if (value && !phoneReg.test(value)) {
        callback(new Error('请输入正确的手机号码'));
    } else {
        callback()
    }
}
// 表单验证
const formRules = reactive<any>({

})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    deptAll({ 'org_id': data.org_id }).then((res) => {
        Object.assign(jobs, res)
    })
    if (data.annex && data.annex.length > 0) {
        const arry1 = data.annex.map((item: any, index: any) => {
            return {
                name: `文件${index + 1}`,
                uri: item
            };
        });
        Object.assign(formDataannex, arry1)
    }
    // console.log(jobs)
    project_name.value = data.project_name
    custom_name.value = data.custom_name
    project_code.value = data.project_code
    customer_demand_name.value = data.customer_demand_name

    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }


}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiCompetitorDetail({
        id: row.id
    })
    setFormData(data)
}


// 提交按钮
const handleSubmit = async () => {
    if (formDataannex.length > 0) {
        formData.annex = formDataannex.map((item) => item.uri)
    }
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiCompetitorEdit(data)
        : await apiCompetitorAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

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


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