"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const t = require("@babel/types");
const traverse_1 = require("@babel/traverse");
const parser = require("@babel/parser");
const utils_1 = require("../utils/utils");
const process_template_1 = require("./process-template");
const { generator } = require('mvvm-template-parser');
// 标记此attr需要被替换或者是单纯的删除
const EMPTYTAG = Symbol('cml-remove-tag');
const compList = [
    'Form',
    'Row',
    'Col',
    'Input',
    'InputNumber',
    'Select',
    'DatePicker',
    'TimePicker',
    'Button',
    'Table',
    'Upload',
    'Radio',
    'Checkbox',
    'Cascader',
    'Switch',
    'Slider',
    'Rate',
    'Modal',
    'PopEdit',
    'Transfer',
    'Pagination',
];
const appComList = ['List', 'List.Item', 'Picker', 'InputItem'];
const extraCompList = ['SortableList', 'SingleImageUpload'];
const fishxList = ['Link'];
let _blocks;
let _pageVar;
let formInfo;
let tplState;
let tplAction;
let conditionObj;
let remoteOptions;
let dataBindingVars;
let hasDate = false;
let hasUpload = false;
let namespace = '';
let initComplete = '';
exports.default = (content, member, blocks, pageVar) => {
    formInfo = [];
    tplState = {};
    tplAction = {};
    conditionObj = {};
    remoteOptions = [];
    dataBindingVars = {};
    _blocks = blocks;
    _pageVar = pageVar;
    // 预处理html模板中的注释，jsx不支持，这个需要优先处理，防止解析 < > 的时候出现问题；
    let parsedContent = (0, process_template_1.preDisappearAnnotation)(content);
    // 预处理：<   >  ==>  _cml_lt_lmc_  _cml_gt_lmc_,这么做的目的为了防止 preParseMustache 解析 > < 中间的内容报错，所以需要将 > < 先转化 gt lt的形式，等 preParseMustache 解析完毕之后即可将其转化回来；
    parsedContent = (0, process_template_1.preParseGtLt)(parsedContent);
    // 预处理 标签内的 {{item.id}} 这种语法jsx无法识别，转化为 {item.id}
    parsedContent = (0, process_template_1.preParseMustache)(parsedContent);
    // 预处理 便签元素属性 :id ====> v-bind:id  @click ====> v-on:click
    parsedContent = (0, process_template_1.preParseSpecialAttr)(parsedContent);
    const ast = parser.parse(parsedContent, {
        plugins: ['jsx'],
    });
    (0, traverse_1.default)(ast, {
        enter(path) {
            const { node } = path;
            if (t.isJSXElement(node)) {
                const tagName = node.openingElement.name.name;
                const { attributes } = node.openingElement;
                const context = {
                    path,
                    node,
                    tagName,
                    attributes,
                };
                tagParser(context, member);
                node.openingElement.attributes = node.openingElement.attributes.filter(attr => attr.name.name !== EMPTYTAG);
            }
        },
        JSXAttribute(path) {
            const { node } = path;
            // class="xxx" ==> className="xxx"
            if (node.name.name === 'class') {
                path.replaceWith(t.jsxAttribute(t.jsxIdentifier('className'), node.value));
            }
            // id="{{id}}-item" ==> id={`${id}-item`}
            // class="{{true ? 'cls1':'cls2'}}" ==> class={true ? 'cls1':'cls2'}
            if ((0, utils_1.isMustacheReactive)(node.value.value)) {
                const attrValue = node.value.value;
                if (attrValue.indexOf('{{') === 0 &&
                    attrValue.lastIndexOf('}}') === attrValue.length - 2) {
                    let content;
                    const val = attrValue.replace(/(?:{{)|(?:}})/gi, '').trim();
                    if (val.indexOf('.') !== -1 && val[0] !== '{' && val[0] !== '[') {
                        let prefix;
                        if (val.indexOf('this') !== -1) {
                            prefix = '';
                        }
                        else if (val.indexOf('$store') !== -1) {
                            collectStoreState(val);
                            prefix = 'this.props.';
                        }
                        else {
                            prefix = member.datas[val.split('.')[0]]
                                ? 'this.state.'
                                : 'this.props.';
                        }
                        content = (0, utils_1.objValueStr2AST)(prefix + val);
                    }
                    else if (member.computeds[val] ||
                        member.datas[val] ||
                        member.props[val]) {
                        content = member.computeds[val]
                            ? t.identifier(val)
                            : t.memberExpression(t.memberExpression(t.thisExpression(), getIdentifier(member, val)), t.identifier(val));
                    }
                    else {
                        content = t.identifier(val);
                    }
                    path.replaceWith(t.jsxAttribute(t.jsxIdentifier(node.name.name), t.jsxExpressionContainer(content)));
                }
                else {
                    const tplArr = [];
                    const expArr = [];
                    attrValue.match(/{{([\s\S]*?)}}/g).forEach(key => {
                        let exp;
                        const val = key.replace(/(?:{{)|(?:}})/gi, '').trim();
                        if (val.indexOf('.') !== -1 && val[0] !== '{' && val[0] !== '[') {
                            let prefix;
                            if (val.indexOf('this') !== -1) {
                                prefix = '';
                            }
                            else if (val.indexOf('$store') !== -1) {
                                collectStoreState(val);
                                prefix = 'this.props.';
                            }
                            else {
                                prefix = member.datas[val.split('.')[0]]
                                    ? 'this.state.'
                                    : 'this.props.';
                            }
                            exp = (0, utils_1.objValueStr2AST)(prefix + val);
                        }
                        else if (member.computeds[val] ||
                            member.datas[val] ||
                            member.props[val]) {
                            exp = member.computeds[val]
                                ? t.identifier(val)
                                : t.memberExpression(t.memberExpression(t.thisExpression(), getIdentifier(member, val)), t.identifier(val));
                        }
                        expArr.push(exp);
                    });
                    const newAttrValue = attrValue.replace(/{{([\s\S]*?)}}/g, '_SPLIT_');
                    newAttrValue.split('_SPLIT_').forEach(str => {
                        tplArr.push(t.templateElement({ raw: str }));
                    });
                    path.replaceWith(t.jsxAttribute(t.jsxIdentifier(node.name.name), t.jsxExpressionContainer(t.templateLiteral(tplArr, expArr))));
                }
            }
        },
    });
    let source = generator(ast).code;
    source = source.replace(/{{/g, '{').replace(/}}/g, '}');
    // 处理组件属性中值为对象时，将对象的key为字符串的情况转换成变量
    const rast = parser.parse(source, {
        plugins: ['jsx'],
    });
    (0, traverse_1.default)(rast, {
        ObjectProperty(path) {
            if (t.isStringLiteral(path.node.key)) {
                path.replaceWith(t.objectProperty(t.identifier(path.node.key.value), path.node.value));
            }
        },
    });
    source = generator(rast).code;
    source = source.replace(/{{/g, '{').replace(/}}/g, '}');
    return {
        hasDate,
        hasUpload,
        formInfo,
        tplState,
        tplAction,
        namespace,
        conditionObj,
        remoteOptions,
        dataBindingVars,
        initComplete,
        tplCode: source,
    };
};
function tagParser(context, member) {
    const { path, node, attributes } = context;
    let { tagName } = context;
    let newtagName = '';
    let tagNameAttrValue = '';
    let tagIdAttrValue = '';
    let onClickFn = '';
    let onChangeFn = '';
    let uploadModelValue = '';
    // 收集wcap组件信息
    if (t.isJSXMemberExpression(node.openingElement.name)) {
        tagName = node.openingElement.name.object.name;
    }
    switch (tagName) {
        case 'Text':
            newtagName = 'span';
            break;
        case 'image':
            newtagName = 'img';
            break;
        case 'cover-view':
        case 'view':
        case 'cell':
        case 'slider-item':
        case 'Block':
        case 'Document':
            newtagName = 'div';
            break;
        default:
            break;
    }
    if (newtagName !== '') {
        node.openingElement.name.name = newtagName;
        if (node.closingElement) {
            node.closingElement.name.name = newtagName;
        }
    }
    attributes.forEach(attr => {
        if (attr.name.name === 'name') {
            tagNameAttrValue = attr.value.value;
        }
        if (attr.name.name === 'id') {
            tagIdAttrValue = attr.value.value;
        }
        if (attr.name.name === 'namespace') {
            namespace = attr.value.value;
        }
        if (attr.name.name === 'initComplete') {
            initComplete = attr.value.value;
        }
    });
    const filterAttr = [];
    attributes.forEach((attr, index) => {
        if (t.isJSXNamespacedName(attr.name) &&
            attr.name.namespace.name === 'v-bind') {
            const bindAttr = attr.name.name.name;
            const bindValue = attr.value.value;
            attr.name = t.jsxIdentifier(bindAttr);
            if (bindAttr !== 'dataSource') {
                conditionObj[`vBind_${tagIdAttrValue}`] = bindValue;
                attr.value = t.jsxExpressionContainer(t.identifier(`vBind_${tagIdAttrValue}`));
            }
            if (bindAttr === 'list' && tagName === 'Select') {
                filterAttr.push('list');
                attributes.find(v => v.name.name === 'options').value =
                    t.jsxExpressionContainer((0, utils_1.objValueStr2AST)(`this.state.${bindValue}`));
            }
        }
        if (t.isJSXNamespacedName(attr.name) &&
            attr.name.namespace.name === 'v-on') {
            const eventName = attr.name.name.name;
            const eventFn = attr.value.value;
            if (eventName === 'click' && ['Table', 'TableEdit'].includes(tagName)) {
                onClickFn = eventFn;
                filterAttr.push('onClick');
            }
            if (eventName === 'change') {
                onChangeFn = eventFn;
            }
            attr.name = t.jsxIdentifier((0, utils_1.camelize)(`on_${eventName}`));
            attr.value = t.jsxExpressionContainer((0, utils_1.objValueStr2AST)(`this.${eventFn}`));
        }
        if (attr.name.name === 'v-if') {
            attr.name.name = EMPTYTAG;
            const ifValue = attr.value.value;
            conditionObj[`vIf_${tagIdAttrValue}`] = ifValue;
            const nextElement = getNextJSXElment(path, path.key + 1); // 查找v-if相邻是否是v-else
            const exp = t.identifier(`vIf_${tagIdAttrValue}`);
            if (nextElement) {
                // 存在v-else
                const left = generatorJSXElement(node);
                const right = generatorJSXElement(nextElement);
                const newNode = t.jsxExpressionContainer(t.conditionalExpression(exp, left, right));
                path.replaceWith(newNode);
            }
            else {
                const right = generatorJSXElement(node);
                const newNode = t.jsxExpressionContainer(t.logicalExpression('&&', exp, right));
                path.replaceWith(newNode);
            }
        }
        // if (attr.name.name === "v-else") {
        //   filterAttr.push('v-else');
        // }
        if (attr.name.name === 'remoteEntry' && tagName === 'Select') {
            filterAttr.push('remoteEntry');
            remoteOptions.push({
                name: `${tagNameAttrValue}_options`,
                value: attr.value.value,
            });
            attributes.find(v => v.name.name === 'options').value =
                t.jsxExpressionContainer((0, utils_1.objValueStr2AST)(`this.state.${tagNameAttrValue}_options`));
        }
    });
    attributes.forEach(attr => {
        if (attr.name.name === 'v-model') {
            filterAttr.push('v-model');
            let valExp;
            let valStateExp;
            let noChange = false;
            let modelValue = attr.value.value;
            if (modelValue.indexOf('.List.Current.') !== -1) {
                const commonSqlArr = modelValue.split('.List.Current.');
                commonSqlArr[0] = `${commonSqlArr[0]}_current`;
                modelValue = commonSqlArr.join('.');
                if (commonSqlArr[1].split('.').length === 1) {
                    valStateExp = (0, utils_1.objValueStr2AST)(`this.state.${commonSqlArr[0]}.${commonSqlArr[1]}`);
                }
                else {
                    valStateExp = t.optionalMemberExpression(t.optionalMemberExpression((0, utils_1.objValueStr2AST)(`this.state.${commonSqlArr[0]}`), t.identifier(commonSqlArr[1].split('.')[0]), false, true), t.identifier(commonSqlArr[1].split('.')[1]), false, true);
                }
            }
            else if (modelValue.indexOf('[') !== -1) {
                noChange = true;
                valStateExp = t.identifier(`this.state.${modelValue}`);
            }
            else {
                valStateExp = (0, utils_1.objValueStr2AST)(`this.state.${modelValue}`);
            }
            dataBindingVars[tagNameAttrValue] = modelValue;
            if (tagName === 'DatePicker' || tagName === 'TimePicker') {
                hasDate = true;
                let dateFormat = tagName === 'DatePicker' ? 'YYYY-MM-DD' : 'HH:mm:ss';
                attributes.forEach(attr => {
                    if (attr.name.name === 'format') {
                        dateFormat = attr.value.value;
                    }
                });
                valExp = t.jsxExpressionContainer(t.conditionalExpression(valStateExp, t.callExpression(t.identifier('moment'), [
                    valStateExp,
                    t.stringLiteral(dateFormat),
                ]), t.stringLiteral('')));
            }
            else {
                valExp = t.jsxExpressionContainer(valStateExp);
            }
            if (tagName === 'Upload') {
                uploadModelValue = modelValue;
                attributes.push(t.jsxAttribute(t.jsxIdentifier('showUploadList'), t.jsxExpressionContainer(t.booleanLiteral(false))));
            }
            else if (tagName === 'Transfer') {
                attributes.push(t.jsxAttribute(t.jsxIdentifier('targetKeys'), valExp));
            }
            else {
                attributes.push(t.jsxAttribute(t.jsxIdentifier('value'), valExp));
            }
            let eventParam;
            let eventBody = [];
            let stateData;
            if (tagName === 'Input' || tagName === 'Radio') {
                eventParam = [t.identifier('e')];
                stateData = 'e.target.value';
            }
            else if (tagName === 'PopEdit' || tagName === 'InputNumber') {
                eventParam = [t.identifier('value')];
                stateData = 'value';
            }
            else if (tagName === 'Select') {
                eventParam = [t.identifier('value'), t.identifier('option')];
                stateData = 'value';
            }
            else if (tagName === 'DatePicker') {
                eventParam = [t.identifier('date'), t.identifier('dateString')];
                stateData = 'dateString';
            }
            else if (tagName === 'TimePicker') {
                eventParam = [t.identifier('time'), t.identifier('timeString')];
                stateData = 'timeString';
            }
            else if (tagName === 'Checkbox') {
                eventParam = [t.identifier('checkedValues')];
                stateData = 'checkedValues';
            }
            else if (tagName === 'Transfer') {
                eventParam = [t.identifier('nextTargetKeys')];
                stateData = 'nextTargetKeys';
            }
            else if (tagName === 'Upload') {
                eventParam = [t.identifier('info')];
            }
            if (tagName !== 'Upload' && !noChange) {
                eventBody = [
                    t.expressionStatement(t.callExpression(t.memberExpression(t.thisExpression(), t.identifier('setState')), [t.objectExpression([(0, utils_1.objPropStr2AST)(modelValue, stateData)])])),
                ];
            }
            if (onChangeFn && !noChange) {
                eventBody.push(t.expressionStatement(t.callExpression((0, utils_1.objValueStr2AST)(`this.${onChangeFn}`), eventParam)));
                attributes.find(attr => attr.name.name === 'onChange').value =
                    t.jsxExpressionContainer(t.arrowFunctionExpression(eventParam, t.blockStatement(eventBody)));
            }
            else if (eventBody.length) {
                attributes.push(t.jsxAttribute(t.jsxIdentifier('onChange'), t.jsxExpressionContainer(t.arrowFunctionExpression(eventParam, t.blockStatement(eventBody)))));
            }
        }
    });
    // 处理Form组件
    if (tagName === 'Form' &&
        !t.isJSXMemberExpression(node.openingElement.name)) {
        formInfo.push(tagNameAttrValue);
        attributes.push(t.jsxAttribute(t.jsxIdentifier('ref'), t.jsxExpressionContainer(t.memberExpression(t.thisExpression(), t.identifier(tagNameAttrValue)))));
        attributes.push(t.jsxAttribute(t.jsxIdentifier('dataBinding'), t.jsxExpressionContainer(t.booleanLiteral(true))));
    }
    if (tagName === 'Upload' && uploadModelValue) {
        hasUpload = true;
        let listType;
        attributes.forEach(attr => {
            if (attr.name.name === 'listType') {
                listType = attr.value.value;
            }
        });
        if (listType === 'picture-card') {
            node.children = [
                t.jsxExpressionContainer(t.identifier(`UploadSPLIT${uploadModelValue}`)),
            ];
        }
        else {
            node.children = [
                t.jsxElement(t.jsxOpeningElement(t.jsxIdentifier('Button'), []), t.jsxClosingElement(t.jsxIdentifier('Button')), [t.jsxText('Click to Upload')]),
            ];
        }
    }
    if (tagName === 'Pagination') {
        attributes.forEach(attr => {
            if (attr.name.name === 'total' && attr.value.value.indexOf('{') === -1) {
                conditionObj[`page_total_${tagIdAttrValue}`] = attr.value.value;
                attr.value = t.jsxExpressionContainer(t.identifier(`page_total_${tagIdAttrValue}`));
            }
            if (attr.name.name === 'current' &&
                attr.value.value.indexOf('{') === -1) {
                conditionObj[`page_current_${tagIdAttrValue}`] = attr.value.value;
                attr.value = t.jsxExpressionContainer(t.identifier(`page_current_${tagIdAttrValue}`));
            }
        });
    }
    if (tagName === 'Transfer') {
        attributes.forEach(attr => {
            if (attr.name.name === 'dataSource') {
                const dataSource = attr.value.value;
                if (dataSource === '[]') {
                    attr.value = t.jsxExpressionContainer(t.arrayExpression());
                }
                else if (dataSource.indexOf('/') !== -1) {
                    attr.value = t.jsxExpressionContainer((0, utils_1.objValueStr2AST)(`this.state.${dataSource.split('/')[3]}`));
                }
                else {
                    attr.value = t.jsxExpressionContainer((0, utils_1.objValueStr2AST)(`this.state.${dataSource}`));
                }
            }
            if (attr.name.name === 'label') {
                const labelVal = attr.value.value;
                attr.name = t.jsxIdentifier('render');
                attr.value = t.jsxExpressionContainer(t.arrowFunctionExpression([t.identifier('item')], (0, utils_1.objValueStr2AST)(`item.${labelVal}`)));
            }
        });
    }
    if (tagName === 'SortableList') {
        attributes.forEach(attr => {
            if (attr.name.name === 'dataSource') {
                const dataSource = attr.value.value;
                if (dataSource === '[]') {
                    attr.value = t.jsxExpressionContainer(t.arrayExpression());
                }
                else if (dataSource.indexOf('/') !== -1) {
                    attr.value = t.jsxExpressionContainer((0, utils_1.objValueStr2AST)(`this.state.${dataSource.split('/')[3]}`));
                }
                else {
                    attr.value = t.jsxExpressionContainer((0, utils_1.objValueStr2AST)(`this.state.${dataSource}`));
                }
            }
        });
    }
    if (['Table', 'TableEdit'].includes(tagName)) {
        let commonSqlName = '';
        attributes.forEach(attr => {
            if (attr.name.name === 'dataSource') {
                const dataSource = attr.value.value;
                if (dataSource === '[]') {
                    attr.value = t.jsxExpressionContainer(t.arrayExpression());
                }
                else if (dataSource.indexOf('/') !== -1) {
                    commonSqlName = dataSource.split('/')[3];
                    attr.value = t.jsxExpressionContainer((0, utils_1.objValueStr2AST)(`this.state.${commonSqlName}`));
                }
                else {
                    attr.value = t.jsxExpressionContainer((0, utils_1.objValueStr2AST)(`this.state.${dataSource}`));
                }
            }
            if (attr.name.name === 'rowKey') {
                const rowkeyVal = attr.value.value.split('.');
                if (rowkeyVal.length === 1) {
                    attr.value = t.jsxExpressionContainer(t.arrowFunctionExpression([t.identifier('record')], (0, utils_1.objValueStr2AST)(`record.${attr.value.value}`)));
                }
                else {
                    attr.value = t.jsxExpressionContainer(t.arrowFunctionExpression([t.identifier('record')], t.optionalMemberExpression((0, utils_1.objValueStr2AST)(`record.${rowkeyVal[0]}`), t.identifier(rowkeyVal[1]), false, true)));
                }
            }
        });
        if (commonSqlName || onClickFn) {
            const clickExp = [];
            if (commonSqlName) {
                clickExp.push(t.expressionStatement(t.callExpression(t.memberExpression(t.thisExpression(), t.identifier('setState')), [
                    t.objectExpression([
                        t.objectProperty(t.identifier(`${commonSqlName}_current`), t.identifier('record')),
                    ]),
                ])));
            }
            if (onClickFn) {
                clickExp.push(t.expressionStatement(t.callExpression((0, utils_1.objValueStr2AST)(`this.${onClickFn}`), [
                    t.identifier('record'),
                    t.identifier('index'),
                ])));
            }
            attributes.push(t.jsxAttribute(t.jsxIdentifier('onRow'), t.jsxExpressionContainer(t.arrowFunctionExpression([t.identifier('record'), t.identifier('index')], t.blockStatement([
                t.returnStatement(t.objectExpression([
                    t.objectProperty(t.identifier('onClick'), t.arrowFunctionExpression([t.identifier('event')], t.blockStatement(clickExp))),
                ])),
            ])))));
        }
    }
    if (compList.indexOf(tagName) !== -1 &&
        member.component.indexOf(tagName) === -1) {
        member.component.push(tagName);
    }
    // 收集app组件信息
    if (appComList.indexOf(tagName) !== -1 &&
        member.mobileComponent.indexOf(tagName) === -1) {
        member.mobileComponent.push(tagName);
    }
    if (extraCompList.indexOf(tagName) !== -1 &&
        member.extraComponent.indexOf(tagName) === -1) {
        member.extraComponent.push(tagName);
    }
    // 收集fishx组件信息
    if (fishxList.indexOf(tagName) !== -1 &&
        member.fishx.indexOf(tagName) === -1) {
        member.fishx.push(tagName);
    }
    if (_blocks.indexOf(tagName) !== -1 &&
        member.pageBlocks.indexOf(tagName) === -1) {
        member.pageBlocks.push(tagName);
    }
    // 处理Table.Column中含有子元素的情况
    if (t.isJSXMemberExpression(node.openingElement.name) &&
        ['Column', 'TableEdit.Column'].includes(node.openingElement.name.property.name)) {
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        let rowKeyExp;
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        let dataIndexValue;
        path.parentPath.node.openingElement.attributes.forEach(attr => {
            if (attr.name.name === 'rowKey') {
                if (t.isJSXExpressionContainer(attr.value)) {
                    rowKeyExp = attr.value.expression.body;
                }
                else {
                    rowKeyExp = (0, utils_1.objValueStr2AST)(`record.${attr.value.value}`);
                }
            }
        });
        attributes.forEach(attr => {
            if (attr.name.name === 'dataIndex') {
                dataIndexValue = attr.value.value;
            }
        });
        const childrens = [];
        node.children.forEach(children => {
            if (t.isJSXElement(children)) {
                let newChildren;
                if (t.isJSXMemberExpression(children.openingElement.name) &&
                    ['Radio', 'Checkbox'].indexOf(children.openingElement.name.object.name) !== -1) {
                    let changeFn;
                    children.openingElement.attributes.forEach(v => {
                        if (t.isJSXNamespacedName(v.name) &&
                            v.name.name.name === 'change') {
                            changeFn = v.value.value;
                            v.name = t.jsxIdentifier('onChange');
                        }
                    });
                    children.openingElement.attributes =
                        children.openingElement.attributes.filter(v => {
                            return ['onChange'].indexOf(v.name.name) === -1;
                        });
                    const onChangeExp = [];
                    if (changeFn) {
                        onChangeExp.push(t.expressionStatement(t.callExpression((0, utils_1.objValueStr2AST)(`this.${changeFn}`), [
                            t.identifier('record'),
                            t.identifier('index'),
                            t.identifier('event'),
                        ])));
                        children.openingElement.attributes.push(t.jsxAttribute(t.jsxIdentifier('onChange'), t.jsxExpressionContainer(t.arrowFunctionExpression([t.identifier('event')], t.blockStatement(onChangeExp)))));
                    }
                    newChildren = children;
                }
                else if (children.openingElement.name.name === 'Button') {
                    children.openingElement.attributes.forEach(v => {
                        if (t.isJSXNamespacedName(v.name) && v.name.name.name === 'click') {
                            const clickFn = v.value.value;
                            v.name = t.jsxIdentifier('onClick');
                            v.value = t.jsxExpressionContainer(t.arrowFunctionExpression([], t.callExpression((0, utils_1.objValueStr2AST)(`this.${clickFn}`), [
                                t.identifier('record'),
                                t.identifier('index'),
                            ])));
                        }
                    });
                    if (!children.children.length) {
                        children.closingElement = t.jsxClosingElement(t.jsxIdentifier('Button'));
                        children.children = [
                            t.jsxExpressionContainer(t.identifier('text')),
                        ];
                    }
                    newChildren = t.jsxElement(t.jsxOpeningElement(t.jsxIdentifier('Button'), children.openingElement.attributes), t.jsxClosingElement(t.jsxIdentifier('Button')), children.children);
                }
                else if (children.openingElement.name.name === 'Link') {
                    children.openingElement.attributes.forEach(v => {
                        if (v.name.name === 'to' && v.value.value.indexOf('{') !== -1) {
                            const url = v.value.value;
                            const urlParam = [];
                            const newUrl = url.replace(/\{([\s\S]*?)\}/g, (match, key) => {
                                urlParam.push(t.identifier(key));
                                return '@';
                            });
                            if (newUrl.indexOf('@') !== -1) {
                                const urlTemp = newUrl.split('@').map((v, i) => {
                                    if (i !== newUrl.split('@').length - 1) {
                                        return t.templateElement({ raw: v }, false);
                                    }
                                    return t.templateElement({ raw: v }, true);
                                });
                                v.value = t.jsxExpressionContainer(t.templateLiteral(urlTemp, urlParam));
                            }
                        }
                    });
                    if (!children.children.length) {
                        children.closingElement = t.jsxClosingElement(t.jsxIdentifier('Link'));
                        children.children = [
                            t.jsxExpressionContainer(t.identifier('text')),
                        ];
                    }
                    newChildren = t.jsxElement(t.jsxOpeningElement(t.jsxIdentifier('Link'), children.openingElement.attributes), t.jsxClosingElement(t.jsxIdentifier('Link')), children.children);
                }
                else if (children.openingElement.name.name === 'a') {
                    children.openingElement.attributes.forEach(v => {
                        if (v.name.name === 'href') {
                            let url = v.value.value;
                            const urlParam = [];
                            let replaceArr = url
                                .replace(/["|'](.*?)["|']/g, '')
                                .replace(/true/g, '')
                                .replace(/false/g, '')
                                .match(/[a-zA-Z]([a-zA-Z]|[0-9]|_|\.)*/g) || [];
                            replaceArr = Array.from(new Set(replaceArr));
                            replaceArr.forEach(ele => {
                                if (_pageVar.find(item => ele.indexOf(item.name) !== -1 && !item.isCommonSql)) {
                                    url = (0, utils_1.newReplaceAll)(url, ele, '@');
                                    urlParam.push(t.identifier(`this.state.${ele}`));
                                }
                                if (ele.indexOf('record.') !== -1) {
                                    url = (0, utils_1.newReplaceAll)(url, ele, '@');
                                    urlParam.push(t.identifier(ele));
                                }
                                if (ele.indexOf('.List.Current.') !== -1) {
                                    url = (0, utils_1.newReplaceAll)(url, ele, '@');
                                    urlParam.push(t.identifier(ele.replace(/[\S]*?\.List\.Current/, 'record')));
                                }
                            });
                            if (url.indexOf('@') !== -1) {
                                const urlTemp = url.split('@').map((v, i) => {
                                    if (i !== url.split('@').length - 1) {
                                        return t.templateElement({ raw: v }, false);
                                    }
                                    return t.templateElement({ raw: v }, true);
                                });
                                v.value = t.jsxExpressionContainer(t.templateLiteral(urlTemp, urlParam));
                            }
                        }
                    });
                    children.openingElement.attributes.push(t.jsxAttribute(t.jsxIdentifier('target'), t.stringLiteral('_blank')));
                    if (!children.children.length) {
                        children.children = [
                            t.jsxExpressionContainer(t.identifier('text')),
                        ];
                    }
                    newChildren = t.jsxElement(t.jsxOpeningElement(t.jsxIdentifier('a'), children.openingElement.attributes), t.jsxClosingElement(t.jsxIdentifier('a')), children.children);
                }
                else {
                    const childTagName = children.openingElement.name.name;
                    if (!children.children.length) {
                        children.closingElement = t.jsxClosingElement(t.jsxIdentifier(childTagName));
                        children.children = [
                            t.jsxExpressionContainer(t.identifier('text')),
                        ];
                    }
                    newChildren = t.jsxElement(t.jsxOpeningElement(t.jsxIdentifier(childTagName), children.openingElement.attributes), t.jsxClosingElement(t.jsxIdentifier(childTagName)), children.children);
                }
                childrens.push(newChildren);
            }
            if (t.isJSXExpressionContainer(children)) {
                childrens.push(t.jsxElement(t.jsxOpeningElement(t.jsxIdentifier('span'), []), t.jsxClosingElement(t.jsxIdentifier('span')), [children]));
                // node.children = [];
                // attributes.push(
                //   t.jsxAttribute(
                //     t.jsxIdentifier("render"),
                //     t.jsxExpressionContainer(
                //       t.arrowFunctionExpression(
                //         [t.identifier('text'), t.identifier('record'), t.identifier('index')],
                //         t.jsxElement(
                //           t.jsxOpeningElement(t.jsxIdentifier('span'), []),
                //           t.jsxClosingElement(t.jsxIdentifier('span')),
                //           [children]
                //         )
                //       )
                //     )
                //   )
                // );
            }
        });
        node.children = [];
        if (!childrens.length) {
            childrens.push(t.jsxExpressionContainer(t.identifier('text')));
        }
        attributes.push(t.jsxAttribute(t.jsxIdentifier('render'), t.jsxExpressionContainer(t.arrowFunctionExpression([
            t.identifier('text'),
            t.identifier('record'),
            t.identifier('index'),
        ], t.jsxElement(t.jsxOpeningElement(t.jsxMemberExpression(t.jsxIdentifier('React'), t.jsxIdentifier('Fragment')), []), t.jsxClosingElement(t.jsxMemberExpression(t.jsxIdentifier('React'), t.jsxIdentifier('Fragment'))), childrens)))));
    }
    // 处理Form.Item中label的宽度问题
    if (t.isJSXMemberExpression(node.openingElement.name) &&
        node.openingElement.name.object.name === 'Form' &&
        node.openingElement.name.property.name === 'Item') {
        let labelWidth = 100;
        let labelText = '';
        attributes.forEach(attr => {
            if (attr.name.name === 'labelWidth') {
                labelWidth = Number(attr.value.value.replace(/(?:{{)|(?:}})/gi, '').trim());
            }
            if (attr.name.name === 'label') {
                labelText = attr.value.value;
            }
        });
        const labelAttr = attributes.find(attr => attr.name.name === 'label');
        labelAttr.value = t.jsxExpressionContainer(t.jsxElement(t.jsxOpeningElement(t.jsxIdentifier('div'), [
            t.jsxAttribute(t.jsxIdentifier('style'), t.jsxExpressionContainer(t.objectExpression([
                t.objectProperty(t.identifier('width'), t.numericLiteral(labelWidth)),
            ]))),
        ]), t.jsxClosingElement(t.jsxIdentifier('div')), [t.jsxText(labelText)]));
        node.children = node.children.filter(v => t.isJSXElement(v));
    }
    if (filterAttr.length) {
        node.openingElement.attributes = attributes.filter(v => {
            return filterAttr.indexOf(v.name.name) === -1;
        });
    }
}
function collectStoreState(val) {
    // $store.userDetail.selectItem.birthday
    // $store.userList.dataSource
    const modelName = val.split('.')[1];
    const param = val.split('.').slice(2);
    if (!tplState[modelName]) {
        tplState[modelName] = {};
    }
    if (param.length === 1) {
        tplState[modelName][param[0]] = null;
    }
    else {
        if (!tplState[modelName][param[0]]) {
            tplState[modelName][param[0]] = {};
        }
        tplState[modelName][param[0]][param[1]] = null;
    }
}
function getIdentifier(member, key) {
    return member.datas[key] ? t.identifier('state') : t.identifier('props');
}
function generatorJSXElement(node) {
    const tag = node.openingElement.name.name;
    const { attributes } = node.openingElement;
    return t.jsxElement(t.jsxOpeningElement(t.jsxIdentifier(tag), attributes), t.jsxClosingElement(t.jsxIdentifier(tag)), node.children);
}
function getNextJSXElment(path, start) {
    let nextElement = null;
    for (let i = start;; i += 1) {
        const nextPath = path.getSibling(i);
        if (!nextPath.node) {
            break;
        }
        else if (t.isJSXElement(nextPath.node)) {
            nextPath.traverse({
                // eslint-disable-next-line no-loop-func, @typescript-eslint/no-loop-func
                JSXAttribute(p) {
                    if (p.node.name.name === 'v-else') {
                        nextElement = nextPath.node;
                        p.remove();
                    }
                },
            });
            if (nextElement) {
                nextPath.remove();
            }
            break;
        }
    }
    return nextElement;
}
