import { get } from '@/utils/http.js';
import { getInfo } from '@/utils/auth.js';

function formatNumber(num) {
    return num;//(Array(4).join('0') + num).slice(-4);
}

async function getNumber(type) {
    const keys = {
        'immediately': 'job.result.immediately_file_id',
        'deadline': 'job.result.deadline_file_id'
    };
    const key = keys[type];
    const num = await get(`/v2/api/sys_properties/increase?properties_key=${key}`);
    let res = '';
    if (num && num.properties_value) {
        res = formatNumber(num.properties_value) + '号';
    }
    return res;
}

async function getAllNumber() {
    // 责令限期改正通知书编号改为:"CC消限字〔2022〕第XXX号"
    // 责令立即改正通知书编号改为:"CC消即字〔2022〕第XXX号"
    const user = getInfo();
    const year = new Date().getFullYear();
    let lgNum = ['〔', year, '〕', '第'];
    let xgNum = ['〔', year, '〕', '第'];
    if (user && user.enforce_org_id) {
        const org = await get(`/v2/api/enforce_organize?query=enforce_org_id==${user.enforce_org_id}`);
        const lg = await getNumber('immediately');
        lgNum.push(formatNumber(lg.properties_value));
        lgNum.push('号');
        const xg = await getNumber('deadline');
        xgNum.push(formatNumber(xg.properties_value));
        xgNum.push('号');
        if (org && org.data && org.data.length > 0) {
            const name = org.data[0].short_name;
            const list1 = [name, '消', '限字'];
            const list2 = [name, '消', '即字'];
            lgNum = [...list2, ...lgNum];
            xgNum = [...list1, ...xgNum];
        }
    }
    return {
        lg: lgNum,
        xg: xgNum,
    }
}

export default {
    data() {
        return {
            immediateNumber: '',
            deadlineNumber: '',
            immediateNumberList: '',
            deadlineNumberList: '',
        }
    },
    mounted () {
        this.loadPdfNumber();
    },
    methods: {
        async loadPdfNumber() {
            const {lg, xg} = await getAllNumber();
            if (lg) {
                this.immediateNumberList = lg;
                this.immediateNumber = lg.join('');
            }
            if (xg) {
                this.deadlineNumberList = xg;
                this.deadlineNumber = xg.join('');
            }
        },
        setupStaticNoticeResult(task, key, value) {
            let res = task.static_notice_result || '{}';
            res = JSON.parse(res);
            if (key == 'immediately') {
                res.immediately = {
                    number: this.immediateNumberList,
                    content: JSON.stringify(value)
                }
            }
            if (key == 'deadline') {
                res.deadline = {
                    number: this.deadlineNumberList,
                    content: JSON.stringify(value)
                }
            }
            return JSON.stringify(res);
        },
    }
}