<template>
    <div class="fullHeight">
        <div class="searchBox whiteBlock">
            <el-form :inline="true" size="medium" :model="searchForm" ref="searchForm">
                <el-form-item label="项目组名称" prop="projectGroupName">
                    <el-input v-model="searchForm.projectGroupName"
                        :placeholder="$t('message.personnelPosition.please_enter')" clearable></el-input>
                </el-form-item>
                <el-form-item>
                    <!-- v-permission="{key: 'renovate', menuPath: '/project/constructionManage/deviceManage'}" -->
                    <el-button type="primary" plain @click="loadCardData">
                        {{ $t("message.personnelPosition.beaconManage.query") }}
                    </el-button>
                    <el-button type="warning" plain @click="resetForm">
                        {{ $t("message.personnelPosition.beaconManage.refresh") }}
                    </el-button>
                    <el-button type="primary" @click="isAddPoint(1)"> 新增 </el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="table_wrap whiteBlock">
            <el-table class="tables" :data="projectGroupList">
                <el-table-column type="index" width="50" align="center"
                    :label="$t('message.personnelPosition.beaconManage.table.index')"></el-table-column>
                <el-table-column prop="projectGroupName" label="项目组名称" align="center"></el-table-column>
                <el-table-column prop="supervisingUnitName" label="监理单位" align="center"></el-table-column>
                <el-table-column prop="epcContractorName" label="EPC承包商" align="center"></el-table-column>
                <el-table-column prop="constructionUnitNames" label="施工单位" align="center"></el-table-column>
                <el-table-column :label="$t('message.personnelPosition.beaconManage.table.operation')" align="center"
                    width="250">
                    <template slot-scope="scope">
                        <div class="tableBtns">
                            <div @click="isAddPoint(2, scope.row)" class="operationText">
                                <img src="@/assets/images/icon-edit.png" width="15px" height="15px" />
                                <span>{{
                                    $t("message.personnelPosition.beaconManage.table.edit")
                                }}</span>
                            </div>
                            <div @click="removePoint(scope.row)" class="operationText">
                                <img src="@/assets/images/icon-delete.png" width="15px" height="15px" />
                                <span>{{
                                    $t("message.personnelPosition.beaconManage.table.delete")
                                }}</span>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <!-- <div slot="empty">{{$t('message.personnelPosition.empty')}}</div> -->
            </el-table>
            <el-pagination class="pagerBox" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="pageNo" :page-sizes="$store.state.PAGESIZRS" :page-size="pageSize"
                layout="total, sizes, prev, pager, next" :total="Number(total)" background></el-pagination>
        </div>
        <!-- 添加卡片弹框 -->
        <el-dialog :modal-append-to-body="false" :title="cardDialogTitle" :visible.sync="cardDialog" width="667px"
            @close="close">
            <div class="dialog_content">
                <el-form size="medium" :model="cardForm" ref="cardForm" :rules="cardFormRules" label-width="125px"
                    class="dialogFormBox">
                    <el-form-item label="项目组名称" prop="projectGroupName">
                        <el-input v-model="cardForm.projectGroupName"
                            :placeholder="$t('message.personnelPosition.please_enter')"></el-input>
                    </el-form-item>

                    <div class="projectTeam" v-for="(ele, index) in cardForm.projectGroupUnitList" :key="ele.id">
                        <i @click="deleteProjectTeam(ele)" class="el-icon-circle-close"></i>
                        <el-form-item label="监理单位" :prop="`projectGroupUnitList[${index}].supervisingUnitId`"
                            :rules="cardFormRules.supervisingUnitId">
                            <el-select v-model="ele.supervisingUnitId"
                                :placeholder="$t('message.personnelPosition.please_select')" filterable>
                                <el-option :label="item.enterpriseName" :value="item.id"
                                    v-for="(item, index) in enterpriseTypeList" :key="index">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="EPC承包商" prop="epcContractorId"
                            :prop="`projectGroupUnitList[${index}].epcContractorId`" :rules="cardFormRules.epcContractorId">
                            <el-select v-model="ele.epcContractorId"
                                :placeholder="$t('message.personnelPosition.please_select')" filterable>
                                <el-option :label="item.enterpriseName" :value="item.id"
                                    v-for="(item, index) in cooperatorList" :key="index">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="施工单位" prop="constructionUnitIds"
                            :prop="`projectGroupUnitList[${index}].constructionUnitIds`"
                            :rules="cardFormRules.constructionUnitIds">
                            <el-select :blur="clearValidateUnit(index, 'constructionUnitIds')" multiple
                                v-model="ele.constructionUnitIds"
                                :placeholder="$t('message.personnelPosition.please_select')" filterable>
                                <el-option :label="item.enterpriseName" :value="item.id"
                                    v-for="(item, index) in cooperatorList" :key="index">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div class="dialog-add">
                        <el-button type="primary" @click="addProjectTeam" icon="el-icon-plus">新增</el-button>
                    </div>
                    <div class="dialog-footer">
                        <el-button class="cancleBtn" @click="cardDialog = false" icon="el-icon-circle-close"
                            size="medium">{{ $t("message.personnelPosition.cancel") }}
                        </el-button>
                        <el-button type="primary" icon="el-icon-circle-check" @click="saveCardFn" size="medium">{{
                            $t("message.personnelPosition.determine") }}
                        </el-button>
                    </div>
                </el-form>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import {
    getEnterpriseTypeList,
} from '@/assets/js/api/laborPerson'
import {
    getCooperatorListApi
} from '@/assets/js/api/cooperationUnit'
import {
    setProjectGroupAdd,
    getProjectGroupPage,
    getProjectGroupById,
    setProjectGroupEdit,
    setProjectGroupDelete,
} from '@/assets/js/api/project'
export default {
    data() {
        return {
            searchForm: {
                projectGroupName: "",
            },
            projectGroupList: [],
            total: 0,
            pageNo: 1,
            pageSize: 10,
            cardDialogTitle: "",
            cardDialog: false,
            cardFormRules: {
                projectGroupName: [
                    {
                        required: true,
                        message: this.$t("message.personnelPosition.required"),
                        trigger: "blur",
                    },
                ],
                supervisingUnitId: [
                    {
                        required: true,
                        message: this.$t("message.personnelPosition.mandatory"),
                        trigger: "change",
                    },
                ],
                epcContractorId: [
                    {
                        required: true,
                        message: this.$t("message.personnelPosition.mandatory"),
                        trigger: "change",
                    },
                ],
                constructionUnitIds: [
                    {
                        required: true,
                        message: this.$t("message.personnelPosition.mandatory"),
                        trigger: "blur",
                    },
                ],
            },
            isAdd: -1,
            enterpriseTypeList: [],
            cooperatorList: [],
            // 项目组
            cardForm: {
                projectGroupName: "",
                projectGroupUnitList: [],
                projectSn: this.$store.state.projectSn,
            },
        };
    },
    mounted() {
        this.loadAllPerson();
        this.loadCardData();
        this.getCooperatorList();
    },
    methods: {
        // 校验施工单位
        clearValidateUnit(index, unitName) {
            if (this.cardForm.projectGroupUnitList[index].constructionUnitIds.length == 0) return;
            this.$refs.cardForm.clearValidate(`projectGroupUnitList[${index}].${unitName}`);
        },
        // 添加
        addProjectTeam() {
            // const every = this.cardForm.projectGroupUnitList.every((item) => {
            //     return item.supervisingUnitId != "" && item.epcContractorId != "" && item.constructionUnitIds != "";
            // });
            // if(!every) {
            //     this.$message.error("请填写完整信息才能添加！");
            //     return
            // }
            this.cardForm.projectGroupUnitList.push({
                id: Date.now(),
                supervisingUnitId: "",
                epcContractorId: "",
                constructionUnitIds: [],
            });
        },
        deleteProjectTeam(row) {
            const findIndex = this.cardForm.projectGroupUnitList.findIndex(item => item.id == row.id);
            if (findIndex > -1) {
                this.cardForm.projectGroupUnitList.splice(findIndex, 1);
            }
        },
        isAddPoint(type, item) {
            this.isAdd = type;
            if (type == 1) {
                this.cardForm = {
                    projectGroupName: "",
                    projectGroupUnitList: [
                        {
                            id: Date.now(),
                            supervisingUnitId: "",
                            epcContractorId: "",
                            constructionUnitIds: [],
                        },
                    ],
                    projectSn: this.$store.state.projectSn,
                };
                this.cardDialogTitle = this.$t("message.laborDev.add2");
            } else if (type == 2) {
                this.cardDialogTitle = this.$t("message.laborDev.btn_edit"); //编辑卡片
                // this.cardForm = JSON.parse(JSON.stringify(item));
                getProjectGroupById({
                    id: item.id,
                    projectSn: this.$store.state.projectSn,
                }).then((res) => {
                    console.log(res)
                    if (res.code == 200) {
                        this.cardForm = {
                            ...res.result,
                            projectGroupUnitList: res.result.projectGroupUnitList.map(item => {
                                return {
                                    ...item,
                                    constructionUnitIds: item.constructionUnitIds.split(","),
                                }
                            }),
                        };
                    }
                })
            }

            this.cardDialog = true;
        },
        removePoint(item) {
            this.$confirm(
                this.$t("message.personnelPosition.beaconManage.table.confirmText") +
                "【" +
                item.projectGroupName +
                "】?",
                this.$t("message.personnelPosition.beaconManage.table.Tips"),
                {
                    type: "warning",
                }
            ).then(() => {
                setProjectGroupDelete({ id: item.id }).then((res) => {
                    this.loadCardData();
                    this.$message.success(
                        this.$t("message.personnelPosition.delete_success")
                    ); //删除成功!
                });
            });
        },
        //获取卡片列表
        loadCardData() {
            getProjectGroupPage({
                projectSn: this.$store.state.projectSn,
                pageNo: this.pageNo,
                pageSize: this.pageSize,
                projectGroupName: this.searchForm.projectGroupName,
            }).then((res) => {
                this.projectGroupList = res.result.records;
                this.total = res.result.total;
            });
        },
        //添加或编辑卡片
        saveCardFn() {
            this.$refs["cardForm"].validate((valid) => {
                if (valid) {
                    const result = this.cardForm.projectGroupUnitList.map(item => {
                        return {
                            ...item,
                            constructionUnitIds: item.constructionUnitIds.join(","),
                        }
                    })
                    if (this.isAdd == 1) {
                        // this.cardForm.floorId = this.currentFloorDetail.floorId
                        setProjectGroupAdd({
                            projectGroupName: this.cardForm.projectGroupName,
                            projectGroupUnitList: result,
                            projectSn: this.$store.state.projectSn,
                        }).then((res) => {
                            this.cardDialog = false;
                            this.loadCardData();
                            this.$message.success(
                                this.$t("message.personnelPosition.add_success")
                            ); //添加成功！
                        });
                    } else if (this.isAdd == 2) {
                        setProjectGroupEdit({ 
                            ...this.cardForm, 
                            projectGroupUnitList: result, 
                        }).then((res) => {
                            this.cardDialog = false;
                            this.loadCardData();
                            this.$message.success(
                                this.$t("message.personnelPosition.edit_success")
                            ); //编辑成功！
                        });
                    }
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        resetForm() {
            this.$refs["searchForm"].resetFields();
            this.loadCardData();
        },

        //查看条数
        handleSizeChange(val) {
            this.pageSize = val;
            this.loadCardData();
        },
        //查看页
        handleCurrentChange(val) {
            this.pageNo = val;
            this.loadCardData();
        },
        close() {
            this.$nextTick(() => {
                this.$refs.cardForm.clearValidate();
            });
        },
        //获取监理单位
        loadAllPerson() {
            // getEnterpriseTypeList
            getCooperatorListApi({
                projectSn: this.$store.state.projectSn,
                pageNo: 1,
                pageSize: -1,
                enterpriseTypeId: 7,
            }).then((res) => {
                this.enterpriseTypeList = res.result.records;
            });
        },
        //获取列表数据
        getCooperatorList() {
            let data = {
                projectSn: this.$store.state.projectSn,
                pageNo: 1,
                pageSize: -1,
                // enterpriseTypeId: this.enterpriseTypeSelectId,
            }
            getCooperatorListApi(data).then((res) => {
                if (res.code == 200) {
                    this.cooperatorList = res.result.records;
                }
            })
        },
    },
};
</script>
<style lang="less" scoped>
.projectTeam:not(:first-child) {
    margin-top: 20px;
}

.projectTeam {
    width: 475px;
    background-color: #F4F4F5;
    padding: 20px 0 1px;
    position: relative;

    .el-icon-circle-close {
        font-size: 20px;
        position: absolute;
        top: 4px;
        right: 4px;
        color: #F56C6C;
        cursor: pointer;
    }
}

.dialog-add {
    display: flex;
    justify-content: center;
    margin-top: 20px;

    /deep/ .el-button {
        background-color: transparent;
        color: #b3b3b3;
        border-color: #b3b3b3;
        border-style: dashed;
    }
}
</style>