<template>
    <div>
        <el-form
            label-width="0px"
            label-position="top"
            :model="addAndEditForm"
            :rules="addAndEditRules"
            ref="addAndEditFormRef"
            :disabled="formType === 2"
        >
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="工程名称" prop="proName">
                        <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="voltage">
                        <el-input
                            clearable
                            maxlength="20"
                            show-word-limit
                            placeholder="请输入电压等级"
                            v-model="addAndEditForm.voltage"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="起止时间" prop="startStopTime">
                        <el-date-picker
                            type="daterange"
                            range-separator="~"
                            style="width: 100%"
                            value-format="yyyy-MM-dd"
                            end-placeholder="结束时间"
                            start-placeholder="开始时间"
                            v-model="addAndEditForm.startStopTime"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="竣工日期" prop="stopTime">
                        <el-date-picker
                            type="date"
                            style="width: 100%"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择竣工日期"
                            v-model="addAndEditForm.stopTime"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="变电站座数" prop="stationNum">
                        <el-input
                            clearable
                            maxlength="20"
                            show-word-limit
                            placeholder="请输入变电站座数"
                            v-model="addAndEditForm.stationNum"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="线路建设规模" prop="lineScale">
                        <el-input
                            clearable
                            maxlength="20"
                            show-word-limit
                            placeholder="请输入线路建设规模"
                            v-model="addAndEditForm.lineScale"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="承包范围" prop="contractRang">
                        <el-input
                            clearable
                            maxlength="50"
                            show-word-limit
                            placeholder="请输入承包范围"
                            v-model="addAndEditForm.contractRang"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="业主单位" prop="ownerUnit">
                        <el-input
                            clearable
                            maxlength="50"
                            show-word-limit
                            placeholder="请输入业主单位"
                            v-model="addAndEditForm.ownerUnit"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="业务单位联系方式" prop="ownerPhone">
                        <el-input
                            clearable
                            maxlength="11"
                            show-word-limit
                            placeholder="请输入业务单位联系方式"
                            v-model="addAndEditForm.ownerPhone"
                        />
                    </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
                                    v-model="row.title"
                                    placeholder="请输入职务"
                                    clearable
                                    maxlength="30"
                                    show-word-limit
                                />
                            </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 keyPersonList"
                                    />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" prop="idCard" label="身份证号" show-overflow-tooltip />
                        <el-table-column align="center" label="工作内容">
                            <template slot-scope="{ row }">
                                <el-input
                                    v-model="row.workContent"
                                    placeholder="请输入工作内容"
                                    clearable
                                    maxlength="50"
                                    show-word-limit
                                />
                            </template>
                        </el-table-column>
                        <el-table-column align="center" prop="zhiW" label="业绩证明材料" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <div
                                    v-for="(item, index) in scope.row.tbFileSourceVoList || []"
                                    :key="index"
                                    style="
                                        display: flex;
                                        align-items: center;
                                        justify-content: center;
                                        margin-bottom: 4px;
                                    "
                                >
                                    <span>材料{{ index + 1 }}</span>
                                    <el-button
                                        type="text"
                                        size="mini"
                                        icon="el-icon-delete"
                                        style="color: #f56c6c"
                                        v-if="formType !== 2"
                                        @click="onHandleDeleteFile(scope.$index, index)"
                                    />
                                </div>
                                <el-button
                                    type="text"
                                    size="mini"
                                    style="color: #409eff"
                                    @click="onHandleUploadFile(scope.$index)"
                                    v-if="scope.row.tbFileSourceVoList.length < 4 && formType !== 2"
                                >
                                    上传
                                </el-button>
                            </template>
                        </el-table-column>
                        <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="20">
                    <el-form-item prop="htKeyFileList">
                        <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.htKeyFileList"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <el-dialog
            title="上传"
            width="40%"
            :visible.sync="uploadOuterVisible"
            v-if="uploadOuterVisible"
            :before-close="
                () => {
                    uploadOuterVisible = false
                }
            "
            append-to-body
        >
            <div class="upload-title">
                <span> 证明材料 </span>
                最多上传4张，仅支持JPG、PNG格式图片
            </div>
            <UploadImg
                :limit="4"
                :file-size="10"
                :multiple="true"
                :file-type="['jpg', 'png', 'jpeg']"
                @deleteFile="deleteFile"
                :file-list.sync="proveFileList"
                :upload-file-url="uploadFileUrl"
            />

            <el-row class="upload-btn-box">
                <el-button size="mini" @click="onCancelInner">取消</el-button>
                <el-button type="primary" size="mini" @click="onConfirmInner">确定</el-button>
            </el-row>
        </el-dialog>

        <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 moment from 'moment'
import UploadImg from '@/components/UploadImg'
import { getKeyPersonListAPI } from '@/api/common'
import { addCompanyPerformanceAPI, editCompanyPerformanceAPI } from '@/api/company-manage/performance-manage'
export default {
    components: {
        UploadImg,
    },
    props: {
        // 1新增 2详情 3编辑
        formType: {
            type: Number,
            default: 1,
        },
        // 编辑行
        editRow: {
            type: Object,
            default: () => {},
        },
    },
    data() {
        const validateStopTime = (rules, value, callback) => {
            if (value === '') {
                callback(new Error('请选择竣工日期'))
                // 使用moment.js判断
            } else if (
                this.addAndEditForm.startStopTime.length > 0 &&
                moment(value).isBefore(moment(this.addAndEditForm.startStopTime[0]))
            ) {
                callback(new Error('竣工日期不能小于开始时间'))
            } else {
                callback()
            }
        }
        return {
            uploadOuterVisible: false,
            uploadFileUrl: process.env.VUE_APP_BASE_API + '/system/file/uploadFiles',
            deleteFileList: [],
            addAndEditForm: {
                proName: '', // 工程名称
                voltage: '', // 电压等级
                startTime: '', // 开始时间
                endTime: '', // 结束时间
                stopTime: '', // 竣工日期
                stationNum: '', // 变电站座数
                lineScale: '', // 线路建设规模
                contractRang: '', // 承包范围
                ownerUnit: '', // 业主单位
                ownerPhone: '', // 业主联系方式
                startStopTime: [], // 起止时间
                htKeyFileList: [], // 合同关键页
                id: '',
            },
            addAndEditRules: {
                proName: [
                    {
                        required: true,
                        message: '请输入工程名称',
                        trigger: 'blur',
                    },
                ],
                voltage: [
                    {
                        required: true,
                        message: '请输入电压等级',
                        trigger: 'blur',
                    },
                ],
                startStopTime: [
                    {
                        required: true,
                        message: '请选择起止时间',
                        trigger: 'change',
                    },
                ],
                stopTime: [
                    {
                        required: true,
                        message: '请输入竣工日期',
                        trigger: 'change',
                    },
                    // 添加一个自定义校验 竣工时间不能小于开始时间
                    { validator: validateStopTime, trigger: 'change' },
                ],
                contractRang: [
                    {
                        required: true,
                        message: '请输入承包范围',
                        trigger: 'blur',
                    },
                ],
                ownerUnit: [
                    {
                        required: true,
                        message: '请输入业主单位',
                        trigger: 'blur',
                    },
                ],
                ownerPhone: [
                    {
                        required: true,
                        message: '请输入业主单位联系方式',
                        trigger: 'blur',
                    },
                    {
                        pattern: /^1[3-9]\d{9}$/,
                        message: '请输入正确的业主单位联系方式',
                        trigger: 'blur',
                    },
                ],
                htKeyFileList: [
                    {
                        required: true,
                        message: '请上传合同关键页',
                        trigger: 'blur',
                    },
                ],
            },
            addTableList: [],
            fileList: [],
            keyPersonList: [], // 关键人员下拉数据
            keyTbCurrentIndex: 0,
            proveFileList: [], // 业绩证明材料
        }
    },
    methods: {
        onHandleAdd() {
            this.addTableList.push({
                title: '',
                userName: '', // 姓名
                workContent: '', // 工作内容
                keyUser: '', // 人员ID
                idCard: '', // 身份证号
                tbFileSourceVoList: [],
            })
        },
        onHandleDelete(row) {
            this.addTableList.splice(row.$index, 1)
        },
        handleSuccess(res) {
            // this.fileList.push(res)
        },
        onCancel() {
            this.$emit('closeDialogOuter')
        },
        onConfirm() {
            this.$refs.addAndEditFormRef.validate(async (valid) => {
                if (valid) {
                    // 组装参数
                    const {
                        proName, // 工程名称
                        voltage, // 电压等级
                        stopTime, // 竣工日期
                        stationNum, // 变电站座数
                        lineScale, // 线路建设规模
                        contractRang, // 承包范围
                        ownerUnit, // 业主单位
                        ownerPhone, // 业主联系方式
                        startStopTime, // 起止时间
                        htKeyFileList, // 合同关键页
                        id,
                    } = this.addAndEditForm
                    const tbFileSourceVoList = []
                    if (htKeyFileList.length > 0) {
                        htKeyFileList.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 = {
                        proName,
                        voltage,
                        startTime: startStopTime[0], // 开始时间
                        endTime: startStopTime[1], // 结束时间
                        stopTime, // 竣工日期
                        stationNum, // 变电站座数
                        lineScale, // 线路建设规模
                        contractRang, // 承包范围
                        ownerUnit, // 业主单位
                        ownerPhone, // 业主联系方式
                        tbCompanyPerfRelList: [],
                        tbFileSourceVoList,
                    }

                    params.tbCompanyPerfRelList = this.addTableList.map((e) => {
                        return {
                            title: e.title,
                            keyUser: e.keyUser,
                            workContent: e.workContent,
                            tbFileSourceVoList: e.tbFileSourceVoList,
                        }
                    })
                    if (this.formType === 3) {
                        params.id = id
                    }
                    const API = this.formType === 1 ? addCompanyPerformanceAPI : editCompanyPerformanceAPI
                    const res = await API(params)
                    if (res.code === 200) {
                        this.$modal.msgSuccess(this.formType === 1 ? '新增成功' : '编辑成功')
                        this.$emit('closeDialogOuter', true)
                    }
                }
            })
        },

        deleteFile() {},
        async getKeyPersonList() {
            const { rows: res } = await getKeyPersonListAPI()
            this.keyPersonList = res
        },
        // 人员选择
        onHandleChange(index, value) {
            this.addTableList[index].userName = this.keyPersonList.find((item) => item.id == value).userName
            this.addTableList[index].idCard = this.keyPersonList.find((item) => item.id == value).idCard
        },
        onCancelInner() {
            this.uploadOuterVisible = false
        },
        onConfirmInner() {
            this.addTableList[this.keyTbCurrentIndex].tbFileSourceVoList = []
            this.proveFileList.forEach((item) => {
                if (item.response && item.response.code === 200) {
                    const { data } = item.response
                    const { fileSuffix, filePath, fileName } = data[0]
                    this.addTableList[this.keyTbCurrentIndex].tbFileSourceVoList.push({
                        fileSuffix,
                        filePath,
                        fileName,
                        fileType: 1,
                    })
                } else {
                    this.addTableList[this.keyTbCurrentIndex].tbFileSourceVoList.push({
                        fileSuffix: item.fileSuffix,
                        filePath: item.filePath,
                        fileName: item.fileName,
                        fileType: 1,
                    })
                }
            })
            this.uploadOuterVisible = false
        },
        onHandleDeleteFile(index, fileIndex) {
            this.addTableList[index].tbFileSourceVoList.splice(fileIndex, 1)
            this.proveFileList.splice(fileIndex, 1)
        },
        onHandleUploadFile(index) {
            this.keyTbCurrentIndex = index
            this.proveFileList = this.addTableList[index].tbFileSourceVoList.map((e) => {
                return {
                    ...e,
                    url: e.filePath,
                }
            })
            this.uploadOuterVisible = true
        },
    },
    watch: {
        editRow: {
            handler(newVal) {
                if (newVal && Object.keys(newVal).length > 0) {
                    const newValueObj = JSON.parse(JSON.stringify(newVal))
                    Object.assign(this.addAndEditForm, { ...newValueObj })
                    this.addAndEditForm.startStopTime = [newValueObj.startTime, newValueObj.endTime]
                    this.addTableList = []
                    this.addTableList = newValueObj.tbCompanyPerfRelList

                    this.addAndEditForm.htKeyFileList = newVal.tbFileSourceVoList.map((e) => {
                        return {
                            ...e,
                            url: e.filePath,
                        }
                    })
                }
            },
            deep: true,
            immediate: true,
        },
    },
    created() {
        this.getKeyPersonList()
    },
}
</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>
