let _width = $(window).width();
let _height = $(window).height();
let width = _width;
let height = _height;

let data = null;
let data_file = './data/data.json';

let fontFamily;

function set_ui() {
    // 设置字体
    let ua = navigator.userAgent.toLowerCase();
    fontFamily = "Khand-Regular";
    if (/\(i[^;]+;( U;)? CPU.+Mac OS X/gi.test(ua)) {
        fontFamily = "PingFangSC-Regular";
    }
    d3.select("body")
        .style("font-family", fontFamily);
}

function draw_treemap() {
    let svg = d3.select('#container')
        .append('svg')
        .attr('width', width)
        .attr('height', height);

    // 定义颜色比例尺
    let color = d3.scaleOrdinal(d3.schemeCategory10);

    function treemap(data) {
        return d3.treemap()
            .size([width, height])
            .padding(1)
            .round(true)
            (d3.hierarchy(data)
                .sum(d => d.value)
                .sort((a, b) => b.value - a.value));
    }

    let root = treemap(data);
    console.log(root.leaves());

    const leaf = svg.selectAll("g")
        .data(root.leaves())
        .join("g")
        .attr("transform", d => `translate(${d.x0},${d.y0})`);
    leaf.append("title")
        .text(d => `${d.ancestors().reverse().map(d => d.data.name).join("/")}\n${d.value}`);

    leaf.append("rect")
        .attr("id", d => d.data.name)
        .attr("fill", d => { while (d.depth > 1) d = d.parent; return color(d.data.name); })
        .attr("fill-opacity", 0.6)
        .attr("width", d => d.x1 - d.x0)
        .attr("height", d => d.y1 - d.y0);

    leaf.append("clipPath")
        .attr("id", d => 'clip-' + d.data.name)
        .append("use")
        .attr("xlink:href", d => "#" + d.data.name);

    leaf.append("text")
        .attr("clip-path", d => "url(#clip-" + d.data.name + ')')
        .selectAll("tspan")
        .data(d => d.data.name.split(/(?=[A-Z][a-z])|\s+/g).concat(d.value))
        .join("tspan")
        .attr("x", 3)
        .attr("y", (d, i, nodes) => `${(i === nodes.length - 1) * 0.3 + 1.1 + i * 0.9}em`)
        .attr("fill-opacity", (d, i, nodes) => i === nodes.length - 1 ? 0.7 : null)
        .text(d => d);
}

function main() {
    d3.json(data_file).then(function (DATA) {
        set_ui();
        data = DATA;
        draw_treemap();
    })
}

main()