<script lang="ts">
import { Component } from 'vue-property-decorator';
import template from './businessInfo.component.html';
import BaseRecordComponent from "hbt-common/components/common/baseRecord.component.vue";
import FormComponent from "hbt-common/components/common/form.component.vue";
import TableComponent from "hbt-common/components/common/table.component.vue";
import BusinessInfoService from "@/service/businessInfo.service";
import FormOption from "hbt-common/models/formOptions";
import BtnOption from "hbt-common/models/btnOptions";
import { Base64 } from 'js-base64';
import mapboxgl from "mapbox-gl";
import MapComponent from "@/components/map.component.vue"

@Component({
    template,
    components: {
        FormComponent,
        TableComponent,
        MapComponent
    },
})
export default class BusinessInfo extends BaseRecordComponent<any> {
    public tableService = new BusinessInfoService();

    public params = {
        name: null,
    } as any;

    public showProtable = false;

    public tableColumn = [] as any;

    public showUpdate = false;

    public updateParams = {
        majorSign: [],
    } as any;

    public subUpdateParams = {} as any;

    public selectData = [];

    public subSelectData = [];

    public isReadonly = false;

    public subIsReadonly = false;


    public fileList1 = [] as any;

    public fileList2 = [] as any;

    public showFile = false;
    public currentUrl = null;

    public subShowUpdate = false;

    public subTitle = '成员信息'

    public currentDetailsTableData = { datas: [] } as any;

    public showDetailsTable = false;

    public showFileModal = false;

    public showFileList = [] as any;

    public showMap = false;
    public center = [118.751353, 31.969568];
    public marker: any;
    public map: any;


    public formActions = [{
        name: "查询",
        value: "search",
        icon: "el-icon-search",
        type: "primary"
    }, {
        name: "清空",
        icon: "el-icon-tickets",
        value: "reset"
    }];

    public tableActions = [{
        name: "添加",
        value: "add",
        icon: "el-icon-plus",
        type: "primary"
    }, {
        name: "批量删除",
        value: "delete",
        plain: true,
        icon: "el-icon-delete",
        type: "danger"
    }];

    public footerActions = [{
        name: "选择全部",
        value: "selectAll",
        type: "primary"
    }, {
        name: "反向选择",
        value: "reverse"
    }];

    public formOptions: FormOption<BtnOption>[] = [{
        name: "企业名称",
        key: "name",
        type: "text",
    },];

    public subActions = [{
        name: "取消",
        value: "cancel"
    }];



    public updateActions = [] as any;

    public updateOptions: FormOption<BtnOption>[] = [] as any;
    public buildUpdateForm() {
        this.updateOptions = [{
            name: "企业名称",
            type: "text",
            key: "name",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
        },
        {
            name: "上级单位",
            type: "text",
            key: "parentId",
            require: false,
            width: "calc(50% - 20px)",
            showError: false,
        },
        {
            name: "统一社会信用代码",
            type: "text",
            key: "socialCode",
            require: true,
            width: "100%",
            showError: false,
        },
        {
            name: "法定代表人",
            type: "select",
            key: "legalLeaderId",
            format: 'legalLeaderName',
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.userList,
        },
        {
            name: "成立日期",
            type: "date",
            key: "establishDate",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            format: "yyyy-MM-dd"
        },
        {
            name: "企业性质",
            type: "select",
            key: "nature",
            format: 'natureName',
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.prevention_enterprise_nature,
        },
        {
            name: "企业规模",
            type: "select",
            key: "scale",
            format: 'scaleName',
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.prevention_enterprise_size,
        },
        {
            name: "员工总数",
            key: "staffNum",
            type: "number",
            width: "calc(50% - 20px)",
            require: true,
            showError: false,
        },
        {
            name: "主要负责人",
            type: "select",
            key: "chargeUserId",
            format: 'chargeUserName',
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.userList,
        },
        {
            name: "监管行业大类",
            type: "select",
            key: "superviseClassify",
            format: 'superviseClassifyName',
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.prevention_regulatory_category,
        },
        {
            name: "监管小类",
            type: "select",
            key: "superviseSubClassify",
            format: 'superviseSubClassifyName',
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.prevention_regulatory_subcategories,
        },
        {
            name: "行政区划",
            type: "text",
            key: "regionDivision",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
        },
        {
            name: "地理位置",
            key: "geoJson",
            type: "btn",
            // width: "calc(0% + 20px)",
            require: true,
            showError: false,
            unit: {
                type: "btn",
                name: this.isReadonly ? "查看定位" : "点击定位",
                value: "fixed",
                btnType: "primary"
            }
        },
        {
            name: "登记机关",
            type: "text",
            key: "registrationAuthority",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
        },
        {
            name: "登记状态",
            type: "select",
            key: "registrationStatus",
            format: "registrationStatusName",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.prevention_registration_status,
        },
        {
            name: "核准日期",
            key: "approvalDate",
            type: "date",
            format: "yyyy-MM-dd",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
        },
        {
            name: "营业期限至",
            key: "termDate",
            type: "date",
            format: "yyyy-MM-dd",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
        },
        {
            name: "企业联系人",
            type: "select",
            key: "contactUserId",
            format: 'contactUserName',
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.userList,
        },
        {
            name: "联系方式",
            type: "text",
            key: "contactUserPhone",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
        },
        {
            name: "注册资本（万元）",
            type: "number",
            key: "registerCapital",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
        },
        {
            name: "占地面积（㎡）",
            type: "number",
            key: "coverArea",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
        },
        {
            name: "经营范围",
            type: "textarea",
            key: "businessScope",
            require: true,
            width: "100%",
            showError: false,
        },
        {
            name: "安全管理机构设置",
            type: "select",
            key: "securityManagementFlag",
            format: "securityManagementFlagName",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: [{
                name: '已设置',
                value: 1,
            }, {
                name: '未设置',
                value: 0,
            }]
        },
        {
            name: "安全管理从业数量",
            type: "number",
            key: "securityManagementNum",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
        },
        {
            name: "安全管理负责人",
            type: "select",
            key: "securityUserId",
            format: 'securityUserName',
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
            datas: this.$store.state.userList,
        },
        {
            name: "联系方式",
            type: "text",
            key: "securityUserPhone",
            require: true,
            width: "calc(50% - 20px)",
            showError: false,
        },
        {
            name: "安标创建情况",
            type: "select",
            key: "safetyLabelStatus",
            format: 'safetyLabelStatusName',
            require: true,
            width: "100%",
            showError: false,
            datas: this.$store.state.prevention_safety_label,
        },
        {
            name: "两大一重情况",
            key: "majorSign",
            format: "majorSignName",
            type: "checkbox",
            width: "calc(100% - 20px)",
            labelWidth: "140px",
            require: true,
            showError: false,
            datas: [{
                name: "不涉及",
                disable: false,
                value: 0
            }, {
                name: "重大危险源",
                disable: this.updateParams.majorSign && this.updateParams.majorSign.includes(0),
                value: 1
            }, {
                name: "重大监管化工工艺",
                disable: this.updateParams.majorSign && this.updateParams.majorSign.includes(0),
                value: 2
            }, {
                name: "重点监管危化品",
                disable: this.updateParams.majorSign && this.updateParams.majorSign.includes(0),
                value: 3
            }],
        },
        {
            name: "企业平面图",
            key: "file1",
            ref: "file",
            type: "upload",
            width: "calc(50% - 20px)",
            showError: false,
            onSucess: this.onSuccess1,
            onMove: this.onRemove1,
            onPreview: this.onPreview,
            autoUpload: true,
            accept: "image/png, image/jpeg,.doc,.docx,.xls,.xlsx,.pdf",
            listType: "text",
            tip: this.isReadonly ? "" : "请上传.pdf,.png,.jpg,.doc.docx,.xls,.xlsx格式文件",
            fileList: this.fileList1,
            btn: [{
                name: "上传附件",
                value: "upload",
                hide: this.isReadonly,
                size: "small",
                type: "primary"
            }]
        },
        {
            name: "企业组织机构",
            key: "file2",
            ref: "file",
            type: "upload",
            width: "calc(50% - 20px)",
            showError: false,
            onSucess: this.onSuccess2,
            onMove: this.onRemove2,
            onPreview: this.onPreview,
            autoUpload: true,
            accept: "image/png, image/jpeg,.doc,.docx,.xls,.xlsx,.pdf",
            listType: "text",
            tip: this.isReadonly ? "" : "请上传.pdf,.png,.jpg,.doc.docx,.xls,.xlsx格式文件",
            fileList: this.fileList2,
            btn: [{
                name: "上传附件",
                value: "upload",
                hide: this.isReadonly,
                size: "small",
                type: "primary"
            }]
        },
        ];
        this.updateActions = [{
            name: "取消",
            value: "cancel"
        }, {
            name: "保存并继续添加",
            value: "saveAndContinue",
            type: "primary",
            hide: this.updateParams.id
        }, {
            name: "保存",
            value: "save",
            type: "primary"
        }];
    }

    created() {
        //
    }


    public buildTable() {
        this.tableColumn.push({ name: '企业名称', key: "name", });
        this.tableColumn.push({ name: '企业负责人', key: "contactUserName", });
        this.tableColumn.push({
            name: '企业性质', key: "nature", render: (data) => {
                return this.$store.getters.prevention_enterprise_nature_map[data.nature]
            }
        });
        this.tableColumn.push({ name: '安全负责人', key: "securityUserName", });
        this.tableColumn.push({ name: '所在行政区划', key: "regionDivision", });
        this.tableColumn.push({
            name: '状态', key: "registrationStatus", render: (data) => {
                return this.$store.getters.prevention_registration_status_map[data.registrationStatus]
            }
        });
    }

    public callback(data, type) {
        if (type) {
            this.params[type] = data;
            this.getTableData();
            return
        }
        // 查询
        if (data.value === "search") {
            this.getTableData()
            // 重置
        } else if (data.value === "reset") {
            this.reset()
            // 反选
        } else if (data.value === "reverse") {
            this.toggleAll()
            // 全选
        } else if (data.value === "selectAll") {
            this.selectAll()
        } else if (data.value === "delete") {
            this.deleteData(this.selectData.map((item: any) => item.id))
        } else if (data.value === 'add') {
            // this.buildUpdateForm()
            this.isReadonly = false
            this.subIsReadonly = false
            this.updateParams = {
                majorSign: [],
                geoJson: JSON.stringify(this.center)
            } as any;
            this.fileList1 = [] as any;
            this.fileList2 = [] as any;
            this.buildUpdateForm();
            this.showUpdate = true
        }
    }

    // 分页数据
    public getTableData() {
        this.tableService.selectByPage(this.params).then(res => {
            this.tableData = res.data as any;
        })
    }
    // 重置数据
    public reset() {
        this.params = {
            pageNum: 1,
            pageSize: 20,
        } as any;
    }

    public getMap(map) {
        this.map = map;
        this.addMarker();
    }
    public addMarker() {
        this.marker = new mapboxgl.Marker({ draggable: !this.isReadonly })
            .setLngLat(this.center)
            .addTo(this.map);
        this.map.flyTo({ center: this.center })
    }

    public onDragEnd() {
        const lngLat = this.marker.getLngLat();
        this.updateParams.locationLng = lngLat.lng;
        this.updateParams.locationLat = lngLat.lat;
        this.center = [lngLat.lng, lngLat.lat];
        this.updateParams.geoJson = JSON.stringify(this.center)
        // this.updateParams.locationName = lngLat.lng+","+lngLat.lat;
        this.handleClose()
    }

    public doSave(goOn?) {
        // 新增清单
        if (this.fileList1.length > 0) {
            let resourceId = this.fileList1.map((item) => {
                return item.id
            })

            let resourceName = this.fileList1.map((item) => {
                return item.name
            })
            this.updateParams.planViewResourceId = resourceId.join(",")
            this.updateParams.planViewResourceName = resourceName.join(",")
        }

        if (this.fileList2.length > 0) {
            let resourceId = this.fileList2.map((item) => {
                return item.id
            })

            let resourceName = this.fileList2.map((item) => {
                return item.name
            })
            this.updateParams.orgResourceId = resourceId.join(",")
            this.updateParams.orgResourceName = resourceName.join(",")
        }

        // 新增
        this.updateParams.chargeUserName = this.$store.getters.user_map[this.updateParams.chargeUserId];
        this.updateParams.contactUserName = this.$store.getters.user_map[this.updateParams.contactUserId];
        this.updateParams.legalLeaderName = this.$store.getters.user_map[this.updateParams.legalLeaderId];
        this.updateParams.securityUserName = this.$store.getters.user_map[this.updateParams.securityUserId];
        this.updateParams.majorSign = this.updateParams.majorSign.join(",");
        this.updateParams.geoJson = JSON.stringify(this.center)
        // this.updateParams.memberNumber = this.updateParams.members.length
        this.tableService.addOrUpdate(this.updateParams, this.updateParams.id ? false : true).then((res) => {
            this.$message.success(!this.updateParams.id ? "新增成功！" : "编辑成功！");
            this.updateParams = {
                majorSign: [],
            } as any
            this.showUpdate = !!goOn;
            this.getTableData();
        })
    }

    public showUpdateModel(id) {
        this.showUpdate = true
    }

    public handleClose() {
        if (this.showMap) {
            this.showMap = false;
            this.marker.remove();
            this.marker = null;
            return
        }
        if (this.showUpdate) {
            this.showUpdate = false;
            this.updateParams = {
                majorHazard: [],
                majorSign:[],
            } as any;
            return
        }
    }


    public toggleAll() {
        this.tableData.datas.forEach((item, index) => {
            (this.$refs.multipleTable as any).toggleRowSelection(item);
        })
    }
    public selectAll() {
        if (!this.selectData.length) {
            this.toggleAll()
        } else {
            this.tableData.datas.forEach((item, index) => {
                const find = this.selectData.find((data: any) => data.id === item.id);
                if (!find) {
                    (this.$refs.multipleTable as any).toggleRowSelection(item);
                }
            })
        }
    }

    public handleSelectionChange(data) {
        this.selectData = data;
    }


    public handleSubSelectionChange(data) {
        this.subSelectData = data;
    }

    public onPreview(file) {
        if (file.type.indexOf("png") >= 0 || file.type.indexOf("jp") >= 0) {
            this.currentUrl = file.url;
            this.showFile = true;
        } else {
            window.open(file.url, "_blank")
        }
    }

    public onSuccess1(res, file, fileList) {
        if (res.code === 200) {
            this.fileList1.push({
                name: res.data.originalName,
                url: res.data.url,
                type: res.data.type,
                id: res.data.id
            })
        } else {
            this.$message.error(res.msg);
        }

    }

    public onRemove1(file, fileList) {
        this.fileList1.splice(this.fileList1.findIndex(item => item.id === file.response.data.id), 1)
    }

    public onSuccess2(res, file, fileList) {
        if (res.code === 200) {
            this.fileList2.push({
                name: res.data.originalName,
                url: res.data.url,
                type: res.data.type,
                id: res.data.id
            })
        } else {
            this.$message.error(res.msg);
        }

    }

    public onRemove2(file, fileList) {
        this.fileList2.splice(this.fileList2.findIndex(item => item.id === file.response.data.id), 1)
    }


    public showModal(rowData, isReadonly) {
        let row = JSON.parse(JSON.stringify(rowData))

        if (isReadonly) {
            this.isReadonly = true;
            this.updateParams = Object.assign({
                natureName: this.$store.getters.prevention_enterprise_nature_map[row.nature],
                scaleName: this.$store.getters.prevention_enterprise_size_map[row.scale],
                superviseClassifyName: this.$store.getters.prevention_regulatory_category_map[row.superviseClassify],
                superviseSubClassifyName: this.$store.getters.prevention_regulatory_subcategories_map[row.superviseSubClassify],
                registrationStatusName: this.$store.getters.prevention_registration_status_map[row.registrationStatus],
                safetyLabelStatusName: this.$store.getters.prevention_safety_label_map[row.safetyLabelStatus],
                majorSignName: !row.majorSign ? null : row.majorSign.split(",").map(item => this.$store.getters.prevention_majorsign_map[item]).join(","),
                securityManagementFlagName: row.securityManagementFlag === 1 ? '已设置' : '未设置'
            }, row)
        } else {
            this.isReadonly = false;
            this.updateParams = row;
            this.updateParams.majorSign = this.updateParams.majorSign.split(',').map((item) => parseInt(item))
        }
        //企业平面图
        if (row.planViewResourceId) {
            this.tableService.getFileUrls({ ids: row.planViewResourceId.split(",") }).then((files: any) => {
                this.fileList1 = files.data.map(item => {
                    return {
                        name: item.originalName,
                        url: item.url,
                        type: item.type,
                        id: item.id
                    }
                })
                this.buildUpdateForm()
            })
        }
        //组织
        if (row.orgResourceId) {
            this.tableService.getFileUrls({ ids: row.orgResourceId.split(",") }).then((files: any) => {
                this.fileList2 = files.data.map(item => {
                    return {
                        name: item.originalName,
                        url: item.url,
                        type: item.type,
                        id: item.id
                    }
                })
                this.buildUpdateForm()
            })
        }
        this.buildUpdateForm()
        this.showUpdate = true
    }

    public showDetails(el, row) {
        const isTarget = el.target.classList.contains("memberNumber");
        const isTargetResourceName = el.target.classList.contains("resourceName");
        if (isTarget) {
            this.tableService.getListDetail({ id: row.id }).then((res: any) => {
                if (res.code === 200) {
                    this.currentDetailsTableData.datas = res.data.members
                    this.currentDetailsTableData.datas.forEach((item, index) => {
                        item.index = index + 1;
                    });
                    this.showDetailsTable = true
                } else {
                    this.$message.error(res.msg);
                }

            })
        }

        if (isTargetResourceName) {
            if (row.resourceId) {
                this.tableService.getFileUrls({ ids: row.resourceId.split(",") }).then((files: any) => {
                    this.showFileList = files.data.map(item => {
                        return {
                            name: item.originalName,
                            url: item.url,
                            type: item.type,
                            id: item.id
                        }
                    })
                    this.showFileModal = true
                })
            }
        }
    }

    public handleTableClose() {
        this.showDetailsTable = false
    }

    public subCallback(data) {
        if (data.value === "add") {
            // this.buildSubForm()
            this.subUpdateParams = {} as any;
            this.subShowUpdate = true
        } else if (data.value === "cancel") {
            this.showUpdate = false
        } else if (data.value === "fixed") {
            this.showMap = true

        } else if (data && data.value.indexOf("save") >= 0) {
            this.doSave(data.value !== "save")
        }
    }


    //查看或者修改
    public showSubModal(row, isReadonly) {
        if (isReadonly) {
            this.subIsReadonly = true
            this.subUpdateParams = row
        } else {
            this.subIsReadonly = false
            this.subUpdateParams = row
        }
        this.subShowUpdate = true
        // this.buildSubForm()
    }

    //删除成员
    public deleteSubData(indexs) {
        this.$confirm('确认删除所选数据', '确认数据', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            for (let i = this.updateParams.members.length - 1; i >= 0; i--) {
                if (indexs.includes(i)) {
                    this.updateParams.members.splice(i, 1)
                }
            }
            this.updateParams.members.forEach((item, index) => {
                item.index = index + 1;
            });
        }).catch(() => {
            //
        });
    }

    public changes(data, item) {
        //是否为两大一重
        //多选 选中不涉及时，其他三项不可选中
        if (item && item.key === 'majorSign') {
            if (!data) {
                data = []
            }
            if (this.updateParams.majorSign.includes(0)) {
                this.updateParams.majorSign = this.updateParams.majorSign.filter(item => item === 0)
                data = this.updateParams.majorSign.filter(item => item === 0)
            }

        }
        this.buildUpdateForm()
    }


    //预览附件
    public previewFile(url, file) {
        if (file.type.indexOf("png") >= 0 || file.type.indexOf("jp") >= 0) {
            this.currentUrl = file.url;
            this.showFile = true;
        } else {
            window.open('http://119.45.186.133:8012/onlinePreview?url=' + encodeURIComponent(Base64.encode(url)), "_blank")
        }
    }

    //下载附件
    public downLoadFile(url, file) {
        let DownUrl = url;
        fetch(DownUrl)
            .then((response) => response.blob())
            .then((res) => {
                //获取文件格式
                var index = DownUrl.lastIndexOf(".");
                //获取文件后缀判断文件格式
                var fileType = DownUrl.substr(index + 1);
                let blob = new Blob([res]);

                const href = window.URL.createObjectURL(blob); //创建下载的链接
                const downloadElement = document.createElement("a");
                downloadElement.href = href;
                downloadElement.target = "_blank";
                downloadElement.download = file.name;
                document.body.appendChild(downloadElement);
                downloadElement.click(); // 点击下载
                document.body.removeChild(downloadElement); // 下载完成移除元素
                window.URL.revokeObjectURL(href); // 释放掉blob对象
            });
    }
}
</script>
<style lang="scss" scoped src="../../common.component.scss"></style>
<style lang="scss" >
.el-tooltip__popper {
    max-width: 400px;
    letter-spacing: 2px;
    border-radius: 4px;


}

.el-tooltip__popper.is-dark {
    background: #000000;
    opacity: 0.8;
    font-size: 12px;
    font-weight: 400;
    padding: 10px;
}
</style>
<style  lang="scss" scoped>
.file-common-list {
    width: 100%;
    padding-bottom: 10px;
    cursor: pointer;
    display: flex;
    align-items: center;
}

.column-cell-render {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.file-common-list:hover {
    .el-icon-document {
        color: #409eff
    }

    .file-list-name {
        color: #409eff
    }
}
</style>