import * as service from '../services';
import { message } from "ant-design-vue";
import * as util from "@/utils/index.js";
export default {
    namespaced: true,
    state: {
        // 查询页
        currencyData: {
            current: 1,
            pageSize: 0,
            total: 0,
            records: []
        },
        // 表格数据
        queryParam: {},
        // list页面查询条件
        insertOrModify: 1,
        //新增修改标志：1-新增，2-修改

        //新增修改
        formData: {},
        //表单数据
        title: '',
        // modal页面标题
        conversion: {
            current: 1,
            pageSize: 0,
            total: 0,
            records: []
        },
        //折算币种
        // 启用数据
        useNo: "",
        validateFlag: true,
        searchCurrency: [],
        // 新增修改页面折算后币种查询条件
        toCurNo: []
    },
    actions: {
        // 列表查询
        async queryCurrency({
            commit,
            dispatch,
            state
        }, payload) {
            // 页面查询条件
            const queryParam = state.queryParam;
            payload.values = util.initQueryParam(payload, queryParam);
            const params = {
                use_yn: "Y",
                ...payload.values
            };
            const data = await service.queryCurrency(params);
            commit("update", {
                currencyData: {
                    current: data.pageNo,
                    pageSize: data.pageSize,
                    total: data.total,
                    records: data.rows
                },
                queryParam: payload.values
            });
        },
        // 新增/修改保存
        async save({
            commit,
            dispatch,
            state
        }, payload) {
            const insertOrModify = state.insertOrModify;
            const conversion = state.conversion.records;
            let flag = true;
            let count = 0;
            // 发生请求之前先判断这算币种是否为空
            for (var item of conversion) {
                count++;
                if (item.key == undefined || item.key == "") {
                    console.log(2);
                    message.error(`第${count}行折算币种编号为空`);
                    flag = false;
                    return;
                }
                if (item.name == undefined || item.name == "") {
                    message.error(`第${count}行折算币种名称为空`);
                    flag = false;
                    return;
                }
                if (item.to_cur_no == undefined || item.to_cur_no == "") {
                    message.error(`第${count}行折算后币种为空`);
                    flag = false;
                    return;
                }
                if (item.show_seqn == undefined || item.show_seqn == "") {
                    message.error(`第${count}行展示顺序为空`);
                    flag = false;
                    return;
                }
            }
            if (flag) {
                // 保存或者修改之前要校验折算币种编号是否重复
                const repeatData = [];
                for (var item of conversion) {
                    if (item.key && item.key != item.validate_key && (item.validate_key != item.key || item.flag != '0000')) {
                        const flag = util.validateRecord("1", 'currency', "key", item.key);
                        if (flag == '0001') {
                            repeatData.push(item.key);
                        } else {
                            item.no = item.no ? item.no : '';
                            item.flag = flag;
                            item.correct_yn = "Y";
                            item.disp_yn = "Y";
                        }
                    }
                }
                if (repeatData.length == 0) {
                    if (insertOrModify == 1) {
                        // 新增
                        const params = payload.values;
                        params.gridData = JSON.stringify(conversion);
                        console.log(params);
                        try {
                            await service.CurrencyInsertController(params);
                            message.success("新增成功！");
                            // commit("queryCurrency");
                            payload.closeMethod();
                        } catch (error) {
                            message.error("新增失败！");
                        }
                    } else {
                        // 修改
                        const params = payload.values;
                        params.allData = JSON.stringify(conversion);
                        params._start = 10014;
                        params._backFromClent = 'Y';
                        try {
                            await service.CurrencyModifyController(params);
                            message.success("修改成功！");
                            // commit("queryCurrency");
                            payload.closeMethod();
                        } catch (error) {
                            message.error("修改失败！");
                        }
                    }
                } else {
                    message.error(`折算币种编号${repeatData.join('、')}已存在！`);
                }
            }
        },
        // 新增/修改页面打开
        async clickInsertOrModifyBtn({
            commit,
            dispatch,
            state
        }, payload) {
            const conversion = {
                current: 1,
                pageSize: 0,
                total: 0,
                records: []
            };
            const data = await service.searchCurrency({
                use_yn: "Y"
            });
            if (payload == undefined) {
                //新增
                const tableKey = await service.getTabKeyRule({
                    tabName: 'currency'
                });
                commit("update", {
                    insertOrModify: 1,
                    title: '币种新增',
                    formData: {
                        key: tableKey.value
                    },
                    conversion,
                    useNo: "",
                    searchCurrency: data.test,
                    validateFlag: true,
                    toCurNo: ''
                });
            } else {
                //修改
                const currencyConversion = await service.CurrencyConversionController({
                    no: payload.no
                });
                currencyConversion.rows.forEach(item => item.from_cur_no = payload.name);
                conversion.records = currencyConversion.rows;
                commit("update", {
                    insertOrModify: 2,
                    title: '币种修改',
                    formData: payload,
                    conversion,
                    useNo: payload.no,
                    searchCurrency: data.test,
                    validateFlag: true,
                    toCurNo: payload.no
                });
            }
        },
        // 新增一行
        async addRows({
            commit,
            dispatch,
            state
        }, payload) {
            let conversion = state.conversion;
            conversion.records.push({
                rowsId: Date.now(),
                use_yn: "Y"
            });
            const name = payload.name;
            if (name) {
                conversion.records.forEach(item => {
                    item.from_cur_no = name;
                });
            }
            commit("update", {
                conversion
            });
        },
        // 删除一行
        async deleteRows({
            commit,
            dispatch,
            state
        }, payload) {
            const conversion = state.conversion;
            if (payload.rowsId) {
                const rowsId = payload.rowsId;
                conversion.records = conversion.records.filter(item => item.rowsId != rowsId);
            } else {
                const no = payload.no;
                conversion.records = conversion.records.filter(item => item.no != no);
            }
            commit("update", {
                conversion
            });
        },
        // 编辑一行
        async updateRows({
            commit,
            dispatch,
            state
        }, payload) {
            if (payload.selectedKey == "key") {
                //修改折后币种编号就判断是否重复
                const conversion = state.conversion.records;
                const newKey = payload.selectedRow.key;
                const no = payload.selectedRow.no;
                // 判断是否重复key
                const flag = conversion.some(item => {
                    return item.key == newKey && item.no != no;
                });
                if (flag) {
                    message.error(`折算币种编号[${newKey}]重复！`);
                } else {
                    commit("update", {
                        conversion: {
                            current: payload.current,
                            pageSize: payload.pageSize,
                            total: payload.total,
                            records: payload.records
                        }
                    });
                }
            } else {
                commit("update", {
                    conversion: {
                        current: payload.current,
                        pageSize: payload.pageSize,
                        total: payload.total,
                        records: payload.records
                    }
                });
            }
        },
        async setStardList({
            commit,
            dispatch,
            state
        }, payload) {
            const conversion = state.conversion;
            conversion.records.forEach(item => {
                if (item.no == payload.no || item.rowsId && item.rowsId == payload.rowsId) {
                    item.to_cur_no = payload.value;
                }
            });
            commit("update", {
                conversion
            });
        }
    },
    mutations: {
        update(state, payload) {
            for (let key in payload) {
                state[key] = payload[key];
            }
        }
    }
}
