<template>
    <div class="app-container">
        <TableModel
            :formLabel="formLabel"
            :showOperation="true"
            :showRightTools="true"
            ref="projectSettingTableRef"
            :columnsList="columnsList"
            :request-api="getProjectSettingListAPI"
        >
            <template slot="btn">
                <el-button
                    plain
                    size="mini"
                    type="primary"
                    icon="el-icon-plus"
                    @click="handleAddOrEdit(1, null)"
                >
                    新增
                </el-button>
            </template>

            <template slot="proType" slot-scope="{ data }">
                <span v-if="data.proType">
                    {{ formatProjectType(data.proType) }}
                </span>
                <span v-else>-</span>
            </template>

            <template slot="proArea" slot-scope="{ data }">
                <el-tag size="mini" type="primary" v-if="data.proArea">
                    {{ formatProjectArea(data.proArea) }}
                </el-tag>
                <span v-else>-</span>
            </template>

            <template slot="type" slot-scope="{ data }">
                <el-tag size="mini" :type="data.type == 0 ? 'info' : 'warning'">
                    {{ data.type == 0 ? '退场证明' : '是否可以多工程入场' }}
                </el-tag>
            </template>

            <template slot="isNeed" slot-scope="{ data }">
                <el-tag
                    size="mini"
                    :type="data.isNeed == 1 ? 'success' : 'info'"
                >
                    {{ data.isNeed == 1 ? '是' : '否' }}
                </el-tag>
            </template>

            <template slot="handle" slot-scope="{ data }">
                <el-button
                    plain
                    size="mini"
                    type="primary"
                    icon="el-icon-edit"
                    @click="handleAddOrEdit(2, data)"
                >
                    修改
                </el-button>
                <el-button
                    size="mini"
                    type="danger"
                    icon="el-icon-delete"
                    @click="handleDelete(data)"
                >
                    删除
                </el-button>
            </template>
        </TableModel>

        <DialogModel
            :dialogConfig="dialogConfig"
            @closeDialogOuter="handleCloseDialog"
        >
            <template slot="outerContent">
                <el-form
                    label-width="auto"
                    ref="formRef"
                    :model="formData"
                    :rules="formRules"
                >
                    <el-form-item label="分公司" prop="subId">
                        <el-select
                            clearable
                            filterable
                            style="width: 100%"
                            placeholder="请选择分公司"
                            v-model="formData.subId"
                        >
                            <el-option
                                :key="item.value"
                                :value="item.value + ''"
                                :label="item.label"
                                v-for="item in subContractorOptions"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="工程类型" prop="proTypeList">
                        <el-select
                            clearable
                            filterable
                            multiple
                            style="width: 100%"
                            placeholder="请选择工程类型"
                            v-model="formData.proTypeList"
                        >
                            <el-option
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                                v-for="item in dict.type.project_type"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="工程所属地区" prop="proAreaList">
                        <el-select
                            clearable
                            filterable
                            multiple
                            style="width: 100%"
                            placeholder="请选择工程所属地区"
                            v-model="formData.proAreaList"
                        >
                            <el-option
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                                v-for="item in dict.type.project_action"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="类型" prop="type">
                        <el-radio-group v-model="formData.type">
                            <el-radio-button :label="0"
                                >退场证明</el-radio-button
                            >
                            <el-radio-button :label="1"
                                >是否可以多工程入场</el-radio-button
                            >
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="是否需要" prop="isNeed">
                        <el-radio-group v-model="formData.isNeed">
                            <el-radio-button :label="1">是</el-radio-button>
                            <el-radio-button :label="0">否</el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                </el-form>

                <el-row class="dialog-footer-btn">
                    <el-button size="medium" @click="handleCloseDialog">
                        取消
                    </el-button>
                    <ComButton
                        size="medium"
                        type="primary"
                        @click="handleConfirm"
                    >
                        确定
                    </ComButton>
                </el-row>
            </template>
        </DialogModel>
    </div>
</template>

<script>
import TableModel from '@/components/TableModel'
import DialogModel from '@/components/DialogModel'
import ComButton from '@/components/ComButton'
import { formLabel, columnsList, dialogConfig } from './config'
import {
    addProjectSettingAPI,
    editProjectSettingAPI,
    deleteProjectSettingAPI,
    getProjectSettingListAPI,
} from '@/api/basic-manage/project-setting/index'
import { getSubCompanySelectListCommonFun } from '@/utils/getCommonData'

export default {
    name: 'ProjectSetting',
    dicts: ['project_type', 'project_action'],
    components: {
        TableModel,
        DialogModel,
        ComButton,
    },
    data() {
        return {
            formLabel,
            columnsList,
            dialogConfig,
            getProjectSettingListAPI,
            subContractorOptions: [],
            formData: {
                subId: '',
                id: null,
                proTypeList: [],
                proAreaList: [],
                type: 0,
                isNeed: 1,
            },
            formRules: {
                subId: [
                    {
                        required: true,
                        trigger: 'change',
                        message: '请选择分公司',
                    },
                ],
                proTypeList: [
                    {
                        type: 'array',
                        required: true,
                        trigger: 'blur',
                        message: '请选择工程类型',
                    },
                ],
                proAreaList: [
                    {
                        type: 'array',
                        required: true,
                        trigger: 'blur',
                        message: '请选择工程所属地区',
                    },
                ],
                type: [
                    {
                        required: true,
                        trigger: 'change',
                        message: '请选择类型',
                    },
                ],
                isNeed: [
                    {
                        required: true,
                        trigger: 'change',
                        message: '请选择是否需要',
                    },
                ],
            },
        }
    },
    async created() {
        const subComList = await getSubCompanySelectListCommonFun()
        this.subContractorOptions = subComList.map((item) => ({
            value: item.id,
            label: item.subCompanyName,
        }))

        formLabel.forEach((item) => {
            if (item.f_model === 'proArea') {
                item.f_selList = this.dict.type.project_action
            }
        })
    },
    methods: {
        handleExport(queryParams) {
            // this.download(
            //     '/bmw/proConfig/export',
            //     queryParams,
            //     '工程配置列表.xlsx',
            // )
        },
        handleAddOrEdit(type, data) {
            this.dialogConfig.outerTitle =
                type === 1 ? '新增工程配置' : '修改工程配置'
            this.dialogConfig.outerWidth = '40%'
            this.dialogConfig.minHeight = ''
            this.dialogConfig.maxHeight = ''
            if (type === 2) {
                const { proArea, isNeed, id, subId, proType, type } = data
                this.formData = {
                    id,
                    proAreaList: proArea.split(','),
                    isNeed,
                    type,
                    subId: subId + '',
                    proTypeList: proType ? proType.split(',') : [],
                }
            } else {
                this.formData = {
                    subId: '',
                    id: null,
                    proTypeList: [],
                    proAreaList: [],
                    type: 0,
                    isNeed: 1,
                }
            }
            this.dialogConfig.outerVisible = true
        },
        handleDelete(data) {
            this.$confirm('确定删除该工程配置吗？', '温馨提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(async () => {
                    const res = await deleteProjectSettingAPI({ id: data.id })
                    if (res.code === 200) {
                        this.$modal.msgSuccess('删除成功')
                        this.$refs.projectSettingTableRef.getTableList()
                    }
                })
                .catch(() => {})
        },
        handleConfirm() {
            return new Promise(async (resolve, reject) => {
                try {
                    this.$refs.formRef.validate(async (valid) => {
                        if (!valid) {
                            reject(new Error('表单验证失败'))
                            return
                        }
                        try {
                            const {
                                id,
                                subId,
                                proTypeList,
                                proAreaList,
                                type,
                                isNeed,
                            } = this.formData
                            const params = {
                                subId,
                                subName: this.subContractorOptions.find(
                                    (item) => item.value == subId,
                                )?.label,
                                proType: proTypeList.join(','),
                                proArea: proAreaList.join(','),
                                type,
                                isNeed,
                            }
                            if (id) {
                                params.id = id
                            }
                            const API = !id
                                ? addProjectSettingAPI
                                : editProjectSettingAPI
                            const res = await API(params)
                            if (res.code === 200) {
                                this.$modal.msgSuccess(
                                    id ? '修改成功' : '新增成功',
                                )
                                this.handleCloseDialog()
                                this.$refs.projectSettingTableRef.getTableList()
                                resolve()
                            } else {
                                this.$modal.msgError(res.msg || '操作失败')
                                reject(new Error(res.msg || '操作失败'))
                            }
                        } catch (error) {
                            this.$modal.msgError(
                                error.message || '操作失败，请稍后重试',
                            )
                            reject(error)
                        }
                    })
                } catch (error) {
                    reject(error)
                }
            })
        },
        handleCloseDialog() {
            this.$refs.formRef.resetFields()
            this.formData = {
                subId: '',
                id: null,
                proTypeList: [],
                proAreaList: [],
                type: 0,
                isNeed: 1,
            }
            this.dialogConfig.outerVisible = false
        },
        formatProjectType(proType) {
            if (!proType) return '-'
            const typeList = proType.split(',')
            return typeList
                .map((type) => {
                    const item = this.dict.type.project_type.find(
                        (item) => item.value == type,
                    )
                    return item ? item.label : type
                })
                .join('、')
        },
        formatProjectArea(proArea) {
            if (!proArea) return '-'
            const areaList = proArea.split(',')
            return areaList
                .map((area) => {
                    const item = this.dict.type.project_action.find(
                        (item) => item.value == area,
                    )
                    return item ? item.label : area
                })
                .join('、')
        },
    },
}
</script>
