<template>
    <div class="app-container" id="project">
        <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="100px"
        >
            <el-form-item label="工程项目名称" prop="proName">
                <el-input
                    v-model="queryParams.proName"
                    placeholder="请输入工程项目名称"
                    clearable
                    maxlength="50"
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新建</el-button>
            </el-col>
            <!--            <el-col :span="1.5">-->
            <!--                <el-button-->
            <!--                    type="warning"-->
            <!--                    plain-->
            <!--                    icon="el-icon-download"-->
            <!--                    size="mini"-->
            <!--                    @click="handleExport"-->
            <!--                    >导入数据</el-button-->
            <!--                >-->
            <!--            </el-col>-->
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">
                    导出数据
                </el-button>
            </el-col>

            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange" border :max-height="650">
            <!-- <el-table-column type="selection" width="55" align="center" /> -->
            <el-table-column width="60" align="center" label="序号" type="index">
                <template slot-scope="scope">
                    <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column label="工程项目名称" align="center" prop="proName" />
            <el-table-column label="实施单位" align="center" prop="impUnitName" :show-overflow-tooltip="true" />
            <el-table-column
                label="工程类型"
                align="center"
                prop="proType"
                :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column label="工程编号" align="center" prop="proCode" :show-overflow-tooltip="true" />
            <el-table-column label="项目中心" align="center" prop="proCenter" :show-overflow-tooltip="true" />
            <el-table-column label="是否匹配i8工程" align="center" prop="isMatchI8" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <div v-if="scope.row.isMatchI8 == '匹配'" style="color: green">{{ scope.row.isMatchI8 }}</div>
                    <div v-if="scope.row.isMatchI8 == '不匹配'" style="color: red">{{ scope.row.isMatchI8 }}</div>
                </template>
            </el-table-column>
            <el-table-column label="合同主体" align="center" prop="contractPart" :show-overflow-tooltip="true" />
            <el-table-column label="项目经理" align="center" prop="proManager" :show-overflow-tooltip="true" />
            <el-table-column label="联系电话" align="center" prop="telphone" :show-overflow-tooltip="true" />
            <el-table-column label="i8工程编号" align="center" prop="externalId" :show-overflow-tooltip="true" />
            <el-table-column label="工程竣工时间" align="center" prop="actualEndDate" :show-overflow-tooltip="true" />
            <el-table-column label="工程状态" align="center" prop="proStatus" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.bm_project_status" :value="scope.row.proStatus" />
                </template>
            </el-table-column>
            <el-table-column label="是否结算" align="center" prop="isSlt" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <div v-if="scope.row.isSlt == 1" style="color: green">{{ '已结算' }}</div>
                    <div v-if="scope.row.isSlt == 0" style="color: red">{{ '未结算' }}</div>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="140">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">
                        编辑
                    </el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改参数配置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="关联i8工程" prop="relatedI8">
                            <el-select
                                v-model="form.relatedI8"
                                placeholder="请选择关联i8工程"
                                style="width: 100%"
                                clearable
                                filterable
                                @change="handleChangeI8Pro"
                            >
                                <el-option
                                    v-for="(item, index) in i8ProOpts"
                                    :key="index"
                                    :label="item.projectName"
                                    :value="item.id"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="i8工程ID" prop="externalId">
                            <el-input v-model="form.externalId" placeholder="请输入i8工程ID" maxlength="50" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="工程名称" prop="proName">
                            <el-input v-model="form.proName" placeholder="请输入工程名称" maxlength="50" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="工程编号" prop="proCode">
                            <el-input v-model="form.proCode" placeholder="请输入工程编号" maxlength="50" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="实施单位" prop="impUnit">
                            <el-select
                                v-model="form.impUnit"
                                filterable
                                placeholder="请选择实施单位"
                                style="width: 100%"
                            >
                                <el-option
                                    v-for="status in impUnitList"
                                    :key="status.value"
                                    :label="status.label"
                                    :value="status.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="工程类型" prop="proTypeId">
                            <el-select v-model="form.proTypeId" placeholder="请选择工程类型" style="width: 100%">
                                <el-option
                                    v-for="keeper in proDataRange"
                                    :key="keeper.value"
                                    :label="keeper.label"
                                    :value="keeper.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="工程状态" prop="proStatus">
                            <el-select
                                v-model="form.proStatus"
                                filterable
                                placeholder="请选择工程状态"
                                style="width: 100%"
                            >
                                <el-option
                                    v-for="(item, index) in proStatusOpts"
                                    :key="index"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="工程性质" prop="proNature">
                            <el-select
                                v-model="form.proNature"
                                filterable
                                placeholder="请选择工程性质"
                                style="width: 100%"
                            >
                                <el-option label="基建" value="0"></el-option>
                                <el-option label="用户工程" value="1"></el-option>
                                <el-option label="技修大改" value="2"></el-option>
                                <el-option label="其它" value="3"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="工程竣工时间" prop="actualEndDate">
                            <el-date-picker
                                v-model="form.actualEndDate"
                                type="date"
                                placeholder="请选择工程竣工时间"
                                value-format="yyyy-MM-dd"
                                style="width: 100%"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="项目经理" prop="proManager">
                            <el-input v-model="form.proManager" placeholder="请输入项目经理姓名" maxlength="20" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="联系电话" prop="telphone">
                            <el-input v-model="form.telphone" placeholder="请输入联系电话" maxlength="11" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="合同主体单位" prop="contractPart">
                            <el-input v-model="form.contractPart" placeholder="请输入合同主体单位" maxlength="50" />
                        </el-form-item>
                    </el-col>

                </el-row>

                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="所属项目中心" prop="proCenter">
                            <el-input v-model="form.proCenter" placeholder="请输入所属项目中心" maxlength="50" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="备注" prop="remark">
                            <el-input
                                type="textarea"
                                placeholder="请输入内容"
                                v-model="form.remark"
                                maxlength="100"
                                show-word-limit
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="是否结算" prop="isSlt" v-if="title=='编辑工程'">
                            <el-select
                                v-model="form.isSlt"
                                filterable
                                placeholder="请选择是否结算"
                                style="width: 100%"
                            >
                                <el-option
                                    v-for="(item, index) in sltStatusOpts"
                                    :key="index"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm" :loading="isLoading">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    addProject,
    delProject,
    getProjectList,
    getProjectListDetail,
    updateProject,
    queryProDataApi,
    getProjectUserList,
    unitTypeList,
    impUnitTypeList,
    getI8ProjectList
} from '@/api/basic/basic'
import axios from 'axios'
import CryptoJS from 'crypto-js'
// import { deptTreeSelect } from '@/api/system/user'
// import Treeselect from '@riophae/vue-treeselect'
// import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
    name: 'BmProject',
    dicts: ['bm_project_status'],
    // components: { Treeselect },
    data() {
        return {
            textarea: '',
            isLoading: false,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表格数据
            projectList: [],
            //字典数据
            // i8工程类型
            i8ProOpts: [
                // {
                //     id: '0024a75450',
                //     htzt: '安徽送变电工程有限公司',
                //     oname: '施工管理部',
                //     pcNo: 'PROJ-2024-0862',
                //     projectName: '安庆市变电站新建工程',
                //     stat: '在建',
                //     textcol1: '第四项目管理部(安庆)',
                //     xmjl: '张先生'
                // }
            ],
            proStatusOpts: [
                { label: '开工准备', value: '0' },
                { label: '在建', value: '1' },
                { label: '停工', value: '2' },
                { label: '完工未竣工', value: '3' },
                { label: '竣工', value: '4' }
            ],
            sltStatusOpts: [
                { label: '未结算', value: 0 },
                { label: '已结算', value: 1 }
            ],
            typeList: [],
            impUnitList: [],
            projectStatuses: [],
            // 部门树选项
            deptOptions: undefined,
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 日期范围
            dateRange: [],
            projectNatures: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                proName: undefined
            },
            // 表单参数
            form: {},
            chosenData: {},
            proDataRange: [],
            proStatusDataRange: [],
            proNatureDataRange: [],
            // 表单校验
            rules: {
                proName: [
                    {
                        required: true,
                        message: '工程项目名称不能为空',
                        trigger: 'blur'
                    }
                ],
                impUnit: [
                    {
                        required: true,
                        message: '实施单位不能为空',
                        trigger: 'blur'
                    }
                ],
                proTypeId: [
                    {
                        required: true,
                        message: '工程类型不能为空',
                        trigger: 'blur'
                    }
                ],
                // proStatus: [
                //     {
                //         required: true,
                //         message: '工程状态不能为空',
                //         trigger: 'blur'
                //     }
                // ],
                proNature: [
                    {
                        required: true,
                        message: '工程性质不能为空',
                        trigger: 'blur'
                    }
                ],
                telphone: [
                    { required: false, message: '手机号不能为空', trigger: 'blur' },
                    {
                        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                        message: '请输入正确的手机号码',
                        trigger: 'blur'
                    }
                ]
            }
        }
    },
    created() {
        this.getType()
        // this.getDeptTree()
        this.getList()
        this.getProjectType()
    },
    methods: {
        // 获取i8工程类型
        async getI8ProType() {
            const url = 'http://sgwpdm.ah.sgcc.com.cn/iws/data-center/dc-security/user/login'
            const password = CryptoJS.MD5('Aa2345!').toString()
            console.log('🚀 ~ getI8ProType ~ password:', password)
            const account = 'jijusystem'

            axios
                .post(
                    url,
                    { account: account, password: password },
                    { headers: { 'Content-Type': 'application/json' } }
                )
                .then(response => {
                    console.log('🚀 ~ response.data:', response.data)
                    const token = response.data.data.token
                    console.log('🚀 ~ token:', token)
                    getI8ProjectList({ token })
                        .then(res => {
                            console.log('🚀 ~ res-i8:', res)
                            this.i8ProOpts = res.data.data
                        })
                        .catch(error => {
                            console.error('请求失败：', error)
                        })
                })
                .catch(error => {
                    console.error('请求失败：', error)
                })
        },
        async getProjectType() {
            let prodataRes = await queryProDataApi('bm_project_type')
            this.proDataRange = prodataRes.data.map(item => {
                return {
                    label: item.dictLabel,
                    value: item.dictValue
                }
            })

            let proStatusdataRes = await queryProDataApi('bm_project_status')
            this.proStatusDataRange = proStatusdataRes.data.map(item => {
                return {
                    label: item.dictLabel,
                    value: item.dictValue
                }
            })

            let proNaturedataRes = await queryProDataApi('bm_project_nature')
            this.proNatureDataRange = proNaturedataRes.data.map(item => {
                return {
                    label: item.dictLabel,
                    value: item.dictValue
                }
            })
        },
        //获取实施单位
        getType() {
            impUnitTypeList().then(response => {
                let matTypeRes = response.data
                let result = []
                matTypeRes.forEach(item => {
                    const parts = item.ancestors.split(',')
                    if (parts.length == 2) {
                        result.push({
                            label: item.deptName,
                            value: item.deptId
                        })
                    }
                })

                this.impUnitList = result
            })
        },
        selecType(id) {
            // this.typeList.forEach(item => {
            //   if(item.id == id){
            //     this.form.typeName = item.name
            //   }
            // });
        },
        /** 查询部门下拉树结构 */
        getDeptTree() {
            deptTreeSelect().then(response => {
                this.deptOptions = response.data
            })
        },
        select(row) {
            // console.log(row.label)
            // this.form.deptName = row.label;
        },

        /** 查询字典类型列表 */
        getList() {
            this.loading = true
            getProjectList(this.queryParams).then(response => {
                this.projectList = response.rows
                this.total = response.total
                this.loading = false
            })
        },
        // 取消按钮
        cancel() {
            this.form = this.chosenData
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                proId: undefined,
                proName: undefined,
                dictType: undefined,
                status: '0',
                remark: undefined
            }
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = []
            this.resetForm('queryForm')
            this.handleQuery()
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = '新增工程'
            this.getType()
            this.getI8ProType()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.proId)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        changeStatus(row) {
            let param = {
                proId: row.proId,
                status: row.status
            }
            updateProject(param).then(response => {
                this.getList()
            })
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.getType()
            this.getI8ProType()
            this.reset()
            getProjectListDetail(row.proId).then(response => {
                this.form = response.data
                this.form.impUnit = Number(this.form.impUnit)
                this.form.relatedI8 = this.form.externalId
            })
            this.open = true
            this.title = '编辑工程'
            // });
        },
        /** 提交按钮 */
        submitForm: function () {
            console.log(this.form, '提交--->>>')
            this.$refs['form'].validate(valid => {
                if (valid) {
                    this.isLoading = true
                    if (this.form.proId != undefined) {
                        updateProject(this.form)
                            .then(response => {
                                this.$modal.msgSuccess('修改成功')
                                this.open = false
                                this.isLoading = false
                                this.getList()
                            })
                            .catch(() => {
                                this.isLoading = false
                            })
                    } else {
                        addProject(this.form)
                            .then(response => {
                                this.$modal.msgSuccess('新增成功')
                                this.open = false
                                this.isLoading = false
                                this.getList()
                            })
                            .catch(() => {
                                this.isLoading = false
                            })
                    }
                }
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const proIds = row.proId || this.ids
            this.$modal
                .confirm('是否确认删除所选择的数据项？')
                .then(function () {
                    return delProject(proIds)
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess('删除成功')
                })
                .catch(() => {})
        },
        /** 导出按钮操作 */
        handleExport() {
          const formatTime = (date) => {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}${month}${day}_${hours}${minutes}${seconds}`;
          };

          const currentTime = formatTime(new Date());
            this.download(
                '/material/bm_project/export',
                {
                    ...this.queryParams,
                    dataCondition: this.ids
                },
                `工程项目_${currentTime}.xlsx`
            )
        },
        /** 刷新缓存按钮操作 */
        // handleRefreshCache() {
        //     refreshCache().then(() => {
        //         this.$modal.msgSuccess('刷新成功')
        //         this.$store.dispatch('dict/cleanDict')
        //     })
        // },
        handleChangeI8Pro(val) {
            console.log('🚀 ~ handleChangeI8Pro ~ val:', val)
            if (!val) {
                this.form.proName = ''
                this.form.externalId = ''
                this.form.proCode = ''
                this.form.proManager = ''
                this.form.contractPart = ''
                this.form.proCenter = ''
                this.form.impUnit = ''
                this.form.proStatus = ''
                this.form.actualEndDate = ''
                return
            }
            const current = this.i8ProOpts.find(item => item.id == val)
            console.log('🚀 ~ handleChangeI8Pro ~ current:', current)
            this.form.proName = current.projectName
            this.form.externalId = current.id
            this.form.proCode = current.pcNo
            this.form.proManager = current.xmjl
            this.form.contractPart = current.htzt
            this.form.proCenter = current.textcol1
            this.form.impUnit = this.impUnitList.find(item => item.label == current.oname)?.value
            this.form.proStatus = this.proStatusOpts.find(item => item.label == current.stat)?.value
            this.form.actualEndDate = current.factEndDt
        }
    }
}
</script>
