<template>
    <div>
        <el-form
            ref="addAndEditFormRef"
            label-width="0px"
            label-position="top"
            :model="addAndEditForm"
            :rules="addAndEditRules"
            :disabled="formType === 2"
        >
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="所属分包商" prop="subId">
                        <el-select
                            clearable
                            filterable
                            style="width: 100%"
                            placeholder="请选择所属分包商"
                            v-model="addAndEditForm.subId"
                            @change="onHandleChangeSubId"
                        >
                            <el-option v-for="item in subList" :key="item.id" :label="item.subName" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item prop="proName">
                        <template #label>
                            <span>项目名称</span>
                            <span style="color: #999; font-size: 12px"> (按合同) </span>
                        </template>
                        <el-input
                            clearable
                            maxlength="30"
                            show-word-limit
                            placeholder="请输入项目名称"
                            v-model="addAndEditForm.proName"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="项目建设单位" prop="consUnit">
                        <el-input
                            clearable
                            maxlength="30"
                            show-word-limit
                            placeholder="请输入项目建设单位"
                            v-model="addAndEditForm.consUnit"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="开竣工日期" prop="startAndEndTime">
                        <el-date-picker
                            type="daterange"
                            range-separator="~"
                            style="width: 100%"
                            value-format="yyyy-MM-dd"
                            end-placeholder="结束时间"
                            start-placeholder="开始时间"
                            v-model="addAndEditForm.startAndEndTime"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="合同身份" prop="htRemark">
                        <el-input
                            clearable
                            maxlength="30"
                            show-word-limit
                            placeholder="请输入合同身份"
                            v-model="addAndEditForm.htRemark"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item prop="money">
                        <template #label>
                            <span>分包商合同额</span>
                            <span style="color: #999; font-size: 12px"> (万元) </span>
                        </template>
                        <el-input
                            clearable
                            show-word-limit
                            placeholder="请输入分包商合同额"
                            v-model="addAndEditForm.money"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="电压等级" prop="voltage">
                        <el-input
                            clearable
                            maxlength="30"
                            show-word-limit
                            placeholder="请输入电压等级"
                            v-model="addAndEditForm.voltage"
                        />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="24">
                    <div class="title-box">
                        <div>分包人员 </div>
                        <el-button icon="el-icon-circle-plus" type="text" @click="onHandleAdd" v-if="formType !== 2">
                            添加
                        </el-button>
                    </div>

                    <el-table :data="addTableList" stripe style="width: 100%">
                        <el-table-column label="序号" width="55" type="index" />
                        <el-table-column align="center" label="担任职务" show-overflow-tooltip>
                            <template slot-scope="{ row }">
                                <el-input
                                    clearable
                                    maxlength="30"
                                    show-word-limit
                                    v-model="row.title"
                                    placeholder="请输入职务"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="姓名">
                            <template slot-scope="scope">
                                <el-select
                                    clearable
                                    filterable
                                    v-model="scope.row.keyUser"
                                    @change="onHandleChange(scope.$index, $event)"
                                >
                                    <el-option
                                        :key="item.id"
                                        :value="item.id + ''"
                                        :label="item.userName"
                                        v-for="item in subKeyPersonList"
                                    />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" prop="idCard" label="身份证号" show-overflow-tooltip />
                        <el-table-column label="操作" align="center" v-if="formType !== 2">
                            <template slot-scope="scope">
                                <el-button
                                    type="text"
                                    style="color: #f56c6c"
                                    icon="el-icon-delete-solid"
                                    @click="onHandleDelete(scope)"
                                />
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="合同关键页" prop="imgList">
                        <template #label>
                            <span>合同关键页</span>
                            <span style="color: #999; font-size: 12px">
                                (合同起始页面、关键页面、竣工报告、相关证明等，一个项目最多上传8张仅支持jpg、png格式图片)
                            </span>
                        </template>
                        <UploadImg
                            :limit="8"
                            :file-size="10"
                            :multiple="true"
                            :file-type="['jpg', 'png', 'jpeg']"
                            @deleteFile="deleteFile"
                            :upload-file-url="uploadFileUrl"
                            :file-list.sync="addAndEditForm.imgList"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <el-row class="upload-btn-box">
            <el-button @click="onCancel">{{ formType !== 2 ? '取消' : '关闭' }}</el-button>
            <el-button type="primary" @click="onConfirm" v-if="formType !== 2">确定</el-button>
        </el-row>
    </div>
</template>

<script>
import UploadImg from '@/components/UploadImg'
import { getSubListAPI, getSubKeyPersonListAPI, deleteImgAPI } from '@/api/common'
import { addSubPerformanceManageAPI, editSubPerformanceManageAPI } from '@/api/sub-manage/sub-performance-manage'
export default {
    components: {
        UploadImg,
    },
    props: {
        // 1新增 2详情 3编辑
        formType: {
            type: Number,
            default: 1,
        },
        // 编辑行
        editRow: {
            type: Object,
            default: () => {},
        },
    },
    data() {
        return {
            uploadOuterVisible: false,
            uploadFileUrl: process.env.VUE_APP_BASE_API + '/system/file/uploadFiles',
            addAndEditForm: {
                subId: '', // 所属分包商
                proName: '', // 项目名称
                consUnit: '', // 项目建设单位
                startTime: '', // 开竣工日期
                endTime: '', // 竣工时间
                htRemark: '', // 合同身份
                money: '', // 分包商合同额
                voltage: '', // 电压等级
                startAndEndTime: [],
                id: '',
                imgList: [],
            },
            addAndEditRules: {
                subId: [
                    {
                        required: true,
                        message: '请选择所属分包商',
                        trigger: 'change',
                    },
                ],
                proName: [
                    {
                        required: true,
                        message: '请输入项目名称',
                        trigger: 'blur',
                    },
                ],
                consUnit: [
                    {
                        required: true,
                        message: '请输入项目建设单位',
                        trigger: 'blur',
                    },
                ],
                startAndEndTime: [
                    {
                        required: true,
                        message: '请选择开竣工日期',
                        trigger: 'change',
                    },
                ],
                htRemark: [
                    {
                        required: true,
                        message: '请输入合同身份',
                        trigger: 'blur',
                    },
                ],
                money: [
                    {
                        required: true,
                        message: '请输入分包商合同额',
                        trigger: 'blur',
                    },
                    {
                        pattern: /^[0-9]+(\.[0-9]{1,2})?$/,
                        message: '请输入正确的金额',
                        trigger: 'blur',
                    },
                ],
                voltage: [
                    {
                        required: true,
                        message: '请输入电压等级',
                        trigger: 'blur',
                    },
                ],
                imgList: [
                    {
                        required: true,
                        message: '请上传合同关键页',
                        trigger: 'change',
                    },
                ],
            },
            addTableList: [],
            fileList: [],
            subList: [],
            subKeyPersonList: [],
            deleteFileList: [],
        }
    },
    methods: {
        onHandleAdd() {
            this.addTableList.push({
                userName: '',
                idCard: '',
                source: 2, // 分包业绩关键人员
                keyUser: '', // 人员id
            })
        },
        onHandleDelete(row) {
            this.addTableList.splice(row.$index, 1)
        },
        handleSuccess(res) {
            // this.fileList.push(res)
        },
        // 获取分包商下拉数据源
        async getSubList() {
            const res = await getSubListAPI()
            this.subList = res.rows
        },

        // 分包商选择时获取人员
        onHandleChangeSubId(subId) {
            // this.addTableList = []

            if (this.addTableList.length > 0) {
                this.addTableList.forEach((item) => {
                    item.keyUser = ''
                    item.userName = ''
                    item.idCard = ''
                })
            }
            this.getSubKeyPersonList(subId)
        },

        // 获取分包商关键人员下拉数据源
        async getSubKeyPersonList(subId) {
            const res = await getSubKeyPersonListAPI({ subId })
            this.subKeyPersonList = res.rows
        },
        onCancel() {
            this.$emit('closeDialogOuter', true)
        },
        onConfirm() {
            this.$refs.addAndEditFormRef.validate(async (valid) => {
                if (valid) {
                    // 组装参数
                    const {
                        subId, // 所属分包商
                        proName, // 项目名称
                        consUnit, // 项目建设单位
                        htRemark, // 合同身份
                        money, // 分包商合同额
                        voltage, // 电压等级
                        startAndEndTime,
                        id,
                        imgList,
                    } = this.addAndEditForm
                    const tbFileSourceVoList = []
                    if (imgList.length > 0) {
                        imgList.forEach((item) => {
                            if (item.response && item.response.code === 200) {
                                const { data } = item.response
                                const { fileSuffix, filePath, fileName } = data[0]
                                tbFileSourceVoList.push({
                                    fileSuffix,
                                    filePath,
                                    fileName,
                                    fileType: 1,
                                })
                            } else {
                                tbFileSourceVoList.push({
                                    fileSuffix: item.fileSuffix,
                                    filePath: item.filePath,
                                    fileName: item.fileName,
                                    fileType: 1,
                                })
                            }
                        })
                    }

                    const params = {
                        subId, // 所属分包商
                        proName, // 项目名称
                        consUnit, // 项目建设单位
                        htRemark, // 合同身份
                        money, // 分包商合同额
                        voltage, // 电压等级
                        startTime: startAndEndTime[0], // 开始时间
                        endTime: startAndEndTime[1], // 结束时间
                        tbCompanyPerfRelList: [],
                        tbFileSourceVoList,
                    }

                    params.tbCompanyPerfRelList = this.addTableList.map((e) => {
                        return {
                            title: e.title,
                            keyUser: e.keyUser,
                        }
                    })
                    if (this.formType === 3) {
                        params.id = id
                    }

                    const filePaths = this.deleteFileList.map((item) => item.filepath)
                    if (filePaths.length > 0) {
                        deleteImgAPI({ filePaths: filePaths.join(',') })
                    }
                    const API = this.formType === 1 ? addSubPerformanceManageAPI : editSubPerformanceManageAPI
                    const res = await API(params)
                    if (res.code === 200) {
                        this.$modal.msgSuccess(this.formType === 1 ? '新增成功' : '编辑成功')
                        this.$emit('closeDialogOuter', true)
                    }
                }
            })
        },

        onHandleChange(index, event) {
            // 判断除了当前行之外的其他行是否已经选择 如果已经选择提示重复
            const isRepeat = this.addTableList.some((item, tIndex) => item.keyUser == event && tIndex !== index)
            if (isRepeat) {
                this.$modal.msgError('人员已选择，不可重复添加')
                this.addTableList[index].keyUser = ''
                return false
            } else {
                this.addTableList[index].idCard = this.subKeyPersonList.find((item) => item.id == event).idCard
            }
        },
        deleteFile(filePath) {
            this.deleteFileList.push(filePath)
        },
        deleteFileListFun() {
            const { imgList } = this.addAndEditForm
            const fileList = [...imgList]
            const deleteFileList = []
            this.deleteFileList.forEach((item) => {
                if (item.isNew) {
                    deleteFileList.push(item.filepath)
                }
            })

            fileList.forEach((item) => {
                if (item.response && item.response.code === 200) {
                    const { data } = item.response
                    const { filePath } = data[0]

                    deleteFileList.push(filePath)
                }
            })

            if (deleteFileList.length > 0) {
                deleteImgAPI({ filePaths: deleteFileList.join(',') })
            }
        },
    },

    watch: {
        editRow: {
            handler(newVal) {
                if (newVal && Object.keys(newVal).length > 0) {
                    const newValueObj = JSON.parse(JSON.stringify(newVal))
                    Object.assign(this.addAndEditForm, { ...newValueObj })
                    this.getSubKeyPersonList(newValueObj.subId)
                    this.addAndEditForm.startAndEndTime = [newValueObj.startTime, newValueObj.endTime]
                    this.addTableList = []
                    this.addTableList = newValueObj.tbCompanyPerfRelList
                    this.addAndEditForm.imgList = newVal.tbFileSourceVoList.map((e) => {
                        return {
                            ...e,
                            url: e.filePath,
                        }
                    })
                }
            },
            deep: true,
            immediate: true,
        },
    },
    created() {
        this.getSubList()
    },
}
</script>

<style lang="scss" scoped>
.upload-title {
    margin-bottom: 10px;
    color: #999;
    font-size: 14px;
    span {
        color: #333;
        font-size: 16px;
    }
}
.title-box {
    padding: 8px 0;
    display: flex;
    align-items: center;

    div {
        margin-right: 10px;
        font-size: 14px;
    }
}

.upload-btn-box {
    padding-top: 10px;
    margin-top: 10px;
    text-align: right;
    border-top: 1px solid #e5e5e5;
}
</style>
