<template>
    <div class="page">
        <headNav title="编辑单位信息"></headNav>
        <div class="content" v-if="formData">
            <van-form ref="form" class="custom-form" validate-first @submit="onSubmit">
                 <!-- title="基础信息" -->
                <van-cell-group>
                    <van-field
                        required
                        v-model="formData.enforce_obj_name"
                        name="enforce_obj_name"
                        label="单位名称"
                        maxlength="50"
                        input-align="right"
                        autocomplete="off"
                        :rules="[{ required: true, message: '请填写用户名' }]"
                    />
                    <van-field
                        required
                        label-width="8em"
                        v-model="formData.credit_code"
                        name="credit_code"
                        maxlength="18"
                        :formatter="formatterCreditCode"
                        label="统一社会信用代码"
                        input-align="right"
                        autocomplete="off"
                        :rules="[{ validator: isCreditCode, message: '请填写统一社会信用代码' }]"
                    />
                    <van-field
                        readonly
                        required
                        right-icon="location-o"
                        input-align="right"
                        label="单位地址"
                        name="enforce_obj_address"
                        :value="formData.enforce_obj_address"
                        @click="showPickerMap"
                        :rules="[{ required: true, message: '请选择单位地址' }]"
                    />
                    <van-field
                        readonly
                        clickable
                        input-align="right"
                        name="registerDate"
                        :value="formData.registerDate"
                        label="成立日期"
                        placeholder="点击选择日期"
                        right-icon="arrow"
                        @click="showRegisterDatePicker=true"
                    />
                    <van-field
                        readonly
                        clickable
                        input-align="right"
                        name="operatingDate"
                        :value="formData.operatingDate"
                        label="营业期限"
                        right-icon="arrow"
                        placeholder="点击选择日期"
                        @click="showOperatingDatePicker=true"
                    />
                    <van-field
                        v-model="formData.legal_person"
                        required
                        name="legal_person"
                        maxlength="50"
                        label="单位法人"
                        autocomplete="off"
                        input-align="right"
                        :rules="[{ required: true, message: '请填写单位法人' }]"
                    />
                    <van-field
                        v-model="formData.legal_person_phone"
                        required
                        name="legal_person_phone"
                        label="联系方式"
                        input-align="right"
                        autocomplete="off"
                        :rules="[{ validator: isMobile, message: '请填写手机号码' }]"
                    />
                    <van-field
                      name="manage_status"
                      input-align="right"
                      required
                      label="经营状态"
                      placeholder="点击选择经营状态"
                      :rules="[{ required: true, message: '请选择经营状态' }]"
                    >
                        <template #input>
                            <van-radio-group v-model="formData.manage_status" direction="horizontal">
                                <van-radio name="0">正常</van-radio>
                                <van-radio name="1">冻结</van-radio>
                                <van-radio name="2">注销</van-radio>
                            </van-radio-group>
                        </template>
                    </van-field>
                </van-cell-group>

                <van-cell-group title="消防信息">
                    <van-field
                        readonly
                        clickable
                        required
                        input-align="right"
                        name="enforce_org_name"
                        :value="formData.enforce_org_name"
                        label="所属辖区"
                        right-icon="arrow"
                        placeholder="点击选择所属辖区"
                        :rules="[{ required: true, message: '请选择所属辖区' }]"
                        @click="chooseOrg"
                    />
                    <van-field
                        readonly
                        clickable
                        required
                        input-align="right"
                        name="objType"
                        :value="formData.objType"
                        label="单位规模"
                        right-icon="arrow"
                        placeholder="点击选择单位规模"
                        :rules="[{ required: true, message: '请选择单位规模' }]"
                        @click="showUnitsizePicker=true"
                    />
                    <van-field
                        readonly
                        clickable
                        required
                        input-align="right"
                        name="placeType"
                        :value="formData.placeType"
                        label="场所类型"
                        right-icon="arrow"
                        placeholder="点击选择场所类型"
                        :rules="[{ required: true, message: '请选择场所类型' }]"
                        @click="showPlacePicker=true"
                    />
                    <van-field
                        name="architecture_type"
                        input-align="right"
                        required
                        label="所在建筑"
                        placeholder="点击选择所在建筑"
                        :rules="[{ required: true, message: '请选择所在建筑' }]"
                    >
                        <template #input>
                            <van-radio-group v-model="formData.architecture_type" direction="horizontal">
                                <van-radio name="1">高层建筑</van-radio>
                                <van-radio name="2">非高层建筑</van-radio>
                            </van-radio-group>
                        </template>
                    </van-field>
                    <van-field name="hole_responsibility" input-align="right" label="消防安全">
                        <template #input>
                            <van-checkbox v-model="formData.hole_responsibility" shape="square">场所负责整栋建筑消防安全</van-checkbox>
                        </template>
                    </van-field>
                    <van-field
                        v-model="formData.area"
                        name="area"
                        maxlength="50"
                        label="面积大小"
                        autocomplete="off"
                        input-align="right"
                        placeholder="请填写单位面积"
                    />
                    <van-field
                        v-model="formData.obj_mass"
                        name="obj_mass"
                        label="单位体量"
                        maxlength="50"
                        autocomplete="off"
                        input-align="right"
                        placeholder="请填写单位体量"
                    />
                </van-cell-group>

                <van-cell-group title="消防联系人">
                    <van-field
                        required
                        label-width="7em"
                        v-model="formData.charge_person"
                        name="charge_person"
                        maxlength="50"
                        label="消防安全责任人"
                        input-align="right"
                        autocomplete="off"
                        :rules="[{ required: true, message: '请填写用户名' }]"
                    />
                    <van-field
                        required
                        v-model="formData.charge_person_phone"
                        name="charge_person_phone"
                        label="联系方式"
                        input-align="right"
                        autocomplete="off"
                        :rules="[{ validator: isMobile, message: '请填写手机号码' }]"
                    />
                    <van-field
                        required
                        label-width="7em"
                        maxlength="50"
                        v-model="formData.manage_person"
                        name="manage_person"
                        label="消防安全管理人"
                        input-align="right"
                        autocomplete="off"
                        :rules="[{ required: true, message: '请填写用户名' }]"
                    />
                    <van-field
                        required
                        v-model="formData.manage_person_phone"
                        name="manage_person_phone"
                        label="联系方式"
                        input-align="right"
                        autocomplete="off"
                        :rules="[{ validator: isMobile, message: '请填写手机号码' }]"
                    />
                </van-cell-group>

                <van-cell-group title="相关文件">
                    <van-field
                        v-model="cers.cer_no"
                        name="cer_no"
                        label="文件编号"
                        maxlength="50"
                        autocomplete="off"
                        input-align="right"
                        placeholder="请填写文件编号"
                    />
                    <van-field
                        required
                        v-model="cers.facility"
                        name="facility"
                        rows="4"
                        maxlength="300"
                        type="textarea"
                        autosize
                        show-word-limit
                        label="消防设施"
                        autocomplete="off"
                        input-align="right"
                        :rules="[{ required: true, message: '请填写消防设施' }]"
                    />
                    <van-field name="fileList" input-align="right" label="证件文件">
                        <template #input>
                            <!-- <van-uploader
                                v-model="cers.fileList"
                                :max-count="1"
                                :before-read="beforeAvatarUpload"
                                :after-read="afterRead"
                                multiple
                                capture="camera"
                                @delete="deleteCerFile"
                            /> -->
                            <van-uploader
                                v-model="cers.fileList"
                                :max-count="1"
                                :before-read="beforeAvatarUpload"
                                :after-read="afterRead"
                                capture="camera"
                            />
                        </template>
                    </van-field>
                </van-cell-group>
                <div style="margin: 16px;">
                    <van-button round block type="info" native-type="submit">提交</van-button>
                </div>
            </van-form>
        </div>

        <van-popup v-model="showRegisterDatePicker" position="bottom">
            <van-datetime-picker
                type="date"
                :min-date="minDate"
                :max-date="maxDate"
                v-model="registerDate"
                @confirm="onConfirmRegisterDate"
                @cancel="showRegisterDatePicker = false"
            />
        </van-popup>

        <van-popup v-model="showOperatingDatePicker" position="bottom">
            <van-datetime-picker
                type="date"
                :min-date="minDate"
                :max-date="maxDate"
                v-model="operatingDate"
                @confirm="onConfirmOperatingDate"
                @cancel="showOperatingDatePicker = false"
            />
        </van-popup>

        <van-popup v-model="showUnitsizePicker" position="bottom">
            <van-picker
                show-toolbar
                :columns="unitSize"
                @confirm="onConfirmUnitSize"
                @cancel="showUnitsizePicker = false"
            />
        </van-popup>

        <van-popup v-model="showPlacePicker" position="bottom">
            <van-picker
                show-toolbar
                :columns="placeTypes"
                value-key="name"
                @confirm="onConfirmPlaceType"
                @cancel="showPlacePicker = false"
            />
        </van-popup>

        <van-popup v-model="showOrgPicker" round position="bottom">
            <van-cascader
                v-model="orgValues"
                title="请选择所属辖区"
                :options="orgOptions"
                :field-names="orgFieldNames"
                @close="showOrgPicker = false"
                @finish="onFinishOrgs"
            />
        </van-popup>

        <v-mask :showOverLay="showOverLay" :tipMsg="tipMsg"></v-mask>
    </div>
</template>

<script>
import headNav from '@/components/headNav.vue';
import { get, put } from '@/utils/http.js';
import { handleProblemImgs } from '@/utils/index';
import mask_overLay from '@/components/overLay_xy.vue';
import { compressAccurately } from "image-conversion";
import { dateFormat, isMobile, isCreditCode, isEmpty } from '@/utils/tool';
import Bus from '@/bus';

export default {
    components: {
		headNav,
		'v-mask': mask_overLay
	},
    inject: ['reload'],
	beforeRouteEnter: (to, from, next) => {
		if (from.name === 'companyInfo') {
			next(vm => {
				if (vm.formData) {
                    vm.reload();
                }
			});
		} else {
			next();
		}
	},
    data () {
        return {
            formData: null,
            showOverLay: false,
            tipMsg: '加载中...',
            registerDate: new Date(),
            showRegisterDatePicker: false,
            operatingDate: new Date(),
            showOperatingDatePicker: false,
            minDate: new Date(1950, 0, 1),
            maxDate: new Date(2050, 11, 31),
            placeTypes: [],
            showPlacePicker: false,
            showUnitsizePicker: false,
            formatStr: 'YYYY-mm-dd',
            unitSize: [
                {
                    k: '1',
                    text: '高危火灾单位'
                },
                {
                    k: '2',
                    text: '消防安全重点单位'
                },
                {
                    k: '3',
                    text: '一般单位'
                },
                {
                    k: '4',
                    text: '其他单位'
                }
            ],
            cers: {
                cer_no: null,
                facility: null,
                fileList: []
            },
            showOrgPicker: false,
            orgOptions: [],
            orgValues: '',
            orgFieldNames: {
                text: 'enforce_org_name',
                value: 'enforce_org_id',
                children: 'sub_orgs',
            },
        }
    },
    computed: {
        objId() {
            return this.$route.params.ID
        }
    },
    mounted () {
        if (this.objId) {
            this.loadComanyInfo();
        }
    },
    methods: {
        isMobile,
        isCreditCode,
        checkOrgLeaf (arr) {
            if (arr && arr.length > 0) {
                const vm = this
                arr.map(item => {
                    if (!item.sub_orgs || item.sub_orgs.length === 0) {
                        item.sub_orgs = undefined
                    } else {
                        vm.checkOrgLeaf(item.sub_orgs)
                    }
                })
            }
        },
        formatterCreditCode(v) {
            return v ? v.toLocaleUpperCase() : '';
        },
        async loadComanyInfo() {
            this.showOverLay = true;
            const res = await get('/v2/api/dictionary/place_type/items');
            if (res && res.length > 0) {
                this.placeTypes = res;
            }
            const orgRes = await get('/v2/api/enforce_organize?show_tree=true&size=100000');
            if (orgRes.data && orgRes.data.length > 0) {
                const orgs = orgRes.data;
                this.checkOrgLeaf(orgs);
                this.orgOptions = orgs;
            }
            const result = await get(`/v2/api/enforce-obj/${this.objId}`);
            if (result) {
                if (result.register_date) {
                    result.registerDate = dateFormat(this.formatStr, new Date(result.register_date));
                }
                if (result.operating_date) {
                    result.operatingDate = dateFormat(this.formatStr, new Date(result.operating_date));
                }
                if (result.enforce_obj_type) {
                    const filters = this.unitSize.filter(item => result.enforce_obj_type == item.k);
                    if (filters.length > 0) {
                        result.objType = filters[0].text;
                    }
                }
                if (result.place_type) {
                    const filters = this.placeTypes.filter(item => result.place_type == item.code);
                    if (filters.length > 0) {
                        result.placeType = filters[0].name;
                    }
                }
                result.manage_status = result.manage_status >= 0 ? String(result.manage_status) : ''
                this.formData = result;
                if (result.certificates && result.certificates.length > 0) {
                    const cer = result.certificates[0];
                    let fileList = [];
                    if (cer.file_ids && cer.file_ids.length > 0) {
                        cer.file_ids.split(',').map(file => {
                            if (file.indexOf('http') >= 0) {
                                fileList.push({
                                    url: file,
                                    isImage: true,
                                });
                            }
                            else {
                                fileList.push({
                                    url: handleProblemImgs(file),
                                    isImage: true,
                                    fileID: file,
                                });
                            }
                        });
                    }
                    // cer.fileList = fileList;
                    this.cers.cer_no = cer.cer_no;
                    this.cers.facility = cer.facility;
                    this.cers.fileList = fileList;
                    // this.$set(this.cers, 'fileList', fileList);
                }
            }
            this.showOverLay = false;
        },
        chooseOrg() {
            if (this.orgOptions && this.orgOptions.length > 0) {
                this.showOrgPicker = true;
            }
            else {
                this.tipMsg = '重新获取组织数据...';
                this.showOverLay = true;
                get('/v2/api/enforce_organize?show_tree=true&size=100000').then(orgRes => {
                    if (orgRes.data && orgRes.data.length > 0) {
                        const orgs = orgRes.data;
                        this.checkOrgLeaf(orgs);
                        this.orgOptions = orgs;
                        const vm = this;
                        setTimeout(() => {
                            vm.showOverLay = false;
                            vm.showOrgPicker = true;
                        }, 1000);
                    }
                });

            }
        },
		showPickerMap() {
			this.$router.push('/pickPlace');
			const vm = this;
			Bus.$on('changePosition', data => {
				if (data) {
					vm.formData.enforce_obj_address = data.address;
					vm.formData.longitude = data.point.lng;
					vm.formData.latitude = data.point.lat;
				}
			})
		},
        onConfirmRegisterDate(date) {
            this.formData.registerDate = dateFormat(this.formatStr, date);
            this.formData.register_date = date;
            this.showRegisterDatePicker = false;
        },
        onConfirmOperatingDate(date) {
            this.formData.operatingDate = dateFormat(this.formatStr, date);
            this.formData.operating_date = date;
            this.showOperatingDatePicker = false;
        },
        onFinishOrgs(v) {
            const option = v.selectedOptions[v.selectedOptions.length - 1];
            this.formData.enforce_org_name = option.enforce_org_name;
            this.formData.enforce_org_id = v.enforce_org_id;
            this.showOrgPicker = false;
        },
        onConfirmUnitSize(v) {
            this.formData.objType = v.text;
            this.formData.enforce_obj_type = v.k;
            this.showUnitsizePicker = false;
        },
        onConfirmPlaceType(v) {
            this.formData.placeType = v.name;
            this.formData.place_type = v.code;
            this.showPlacePicker = false;
        },
        beforeAvatarUpload(file) {
            console.debug('file1: ', file);
			const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
			if (!isJpgOrPng) {
				this.$toast.fail("图片只能是 JPG 或 PNG 格式!");
				return false;
			}
			this.showOverLay = true;
			this.tipMsg = '图片处理中';
			return new Promise((resolve) => {
				compressAccurately(file, {
					size: 100, //图片大小压缩到100kb
					// width: 1280, //宽度压缩到1280
				})
				.then((res) => {
					this.showOverLay = false;
                    console.debug('file2: ', res);
					resolve(res);
				});
			});
		},
        afterRead(file) {
            console.log('afterRead: ', file);
			if (file && file.file && file.file.size > 2000000) {
				let canvas = document.createElement('canvas');
				let context = canvas.getContext('2d');
				let img = new Image();
				img.src = file.content;
				img.onload = () => {
					canvas.width = img.width;
					canvas.height = img.height;
					context.drawImage(img, 0, 0, img.width, img.height);
					let base_img = canvas.toDataURL(file.file.type, 0.75);
					const blodBin = atob(base_img.split(',')[1]);
					let data = [];
					for (let i = 0; i < blodBin.length; i++) {
						data.push(blodBin.charCodeAt(i));
					}
					let blob1 = new Blob([new Uint8Array(data)], { type: 'image/png' });
					let file1 = new File([blob1], new Date().getTime() + '.png');
					file.file = file1;
				};
			}
		},
        deleteCerFile(file) {
            if (file && this.cers.fileList.length > 0) {
                for (let index = 0; index < this.cers.fileList.length; index++) {
                    const item = this.cers.fileList[index];
                    if (file.fileID == item.fileID) {
                        this.cers.fileList.splice(index, 1);
                        break;
                    }
                }
            }
        },
        uploadFile(data) {
            let name = data.file.name;
			if (!name || name.length == 0) {
				name = Date.now() + '.jpeg';
			}
            const form = new FormData();
            form.append('fileName', name);
            form.append('fileBinary', data.file);
            this.$http.post('/v2/api/file', form).then(res => {
                if (res && res.data && res.data.id) {
                    data.fileID = res.data.id;
                    this.checkFile();
                }
            })
        },
        checkFile() {
            let have = false;
            if (this.cers.fileList.length > 0) {
                for (let index = 0; index < this.cers.fileList.length; index++) {
                    const item = this.cers.fileList[index];
                    if (!item.url && !item.fileID) {
                        have = true;
                        this.uploadFile(item);
                        break;
                    }
                }
            }
            if (!have) {
                this.commitFormData();
            }
        },
        commitFormData() {
            this.showOverLay = true;
            const obj = Object.assign({}, this.formData);
            obj.architecture_type = parseInt(obj.architecture_type);
            obj.hole_responsibility = obj.hole_responsibility == true ? 1 : 0;
            obj.enforce_obj_type = parseInt(obj.enforce_obj_type);
            const files = Object.assign({}, this.cers);
            if (files.fileList.length > 0) {
                let ids = [];
                files.fileList.map(item => {
                    if (item.fileID) {
                        ids.push(item.fileID);
                    }
                });
                files.file_ids = ids.join(',');
            }
            obj.certificates = [files];
            put(`/v2/api/enforce-obj/${this.objId}`, obj).then(result => {
                this.showOverLay = false;
                this.$toast.success('提交成功');
                this.$router.back();
            })
        },
        onSubmit() {
            if (isEmpty(this.formData.enforce_obj_name)) {
                this.$toast.fail("请填写用户名");
                return false;
            }
            if (isEmpty(this.formData.credit_code)) {
                this.$toast.fail("请填写统一社会信用代码");
                return false;
            }
            if (isEmpty(this.formData.enforce_obj_address)) {
                this.$toast.fail("请选择单位地址");
                return false;
            }
            if (isEmpty(this.formData.enforce_obj_type)) {
                this.$toast.fail("请选择单位规模");
                return false;
            }
            if (isEmpty(this.formData.place_type)) {
                this.$toast.fail("请选择场所类型");
                return false;
            }
            if (isEmpty(this.formData.architecture_type)) {
                this.$toast.fail("请选择所在建筑");
                return false;
            }

            if (isEmpty(this.cers.facility)) {
                this.$toast.fail("请输入消防设施");
                return false;
            }
            this.$refs.form.validate().then(res => {
                if (!res) {
                    this.showOverLay = true;
                    this.checkFile();
                }
            });
        }
    }
}
</script>

<style lang="scss">
.custom-form {
    .van-field__error-message {
        text-align: right;
    }
}
</style>

<style lang="scss" scoped>

</style>
