import {
  select,
  csv,
  scaleLinear,
  scaleOrdinal,
  extent,
  axisLeft,
  axisBottom,
  format,
  brush,
  stack,
} from 'd3';

var keys = ['Teaching', 'Research', 'Citations', 'Industry_income', 'International_outlook']

// 內容
const margin = 50;
const barPadding = 2;
const width = 19200 - margin * 2;
const height = 300;

// 提示框
const legendData = [
  { key: 'Teaching', color: 'DodgerBlue' },
  { key: 'Research', color: 'purple' },
  { key: 'Citations', color: 'green' },
  { key: 'Industry_income', color: 'orange' },
  { key: 'International_outlook', color: 'red' },
];

const rectSize = 25; // 矩形的大小
const rectSpacing = 150; // 矩形之间的间距
const textX = rectSize + 5; // 文本标签的水平偏移

const render = data => {
  
  // 清除上一次的畫布
  d3.select('svg').selectAll('*').remove();
  
  // Keys
  swap_keys();
	
  // Create the SVG wrapper
  const svg = d3.select('body')
    .append('svg')
    .attr('width', width + margin * 2)
    .attr('height', height + margin * 3)
    .append('g')
    .attr('transform', `translate(${margin},${margin})`);
  
  var stack_data = d3.stack().keys(keys)(data)
  // console.log(stack_data)
  
	// Y-Axis
	var yMax = d3.max(data, d => keys.reduce((acc, k) => acc + d[k], 0));
	var y = d3.scaleLinear().domain([0, yMax]).range([height,0])
	var yAxis = d3.axisLeft(y);
  
	// X-Axis
	var x = d3.scaleBand()
            .domain(data.map(d => d.name)) // 使用学校名称作为 x 轴的域
            .range([0, width])
            .padding(0.5); // 可调整间距
	var xAxis = d3.axisBottom(x).tickSize(0);
  
  
  // Key Color
  var colorScale = d3.scaleOrdinal()
  									 .domain(keys)
  									 .range(['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd']); 

  // Append rectangles
  svg.selectAll('g')
    .data(stack_data).enter()
  .append('g')
  .attr('class', d => `group-${d.key}`) 
    .selectAll('rect')
    .data(d => d).enter()
  .append('rect')
    .attr('x',  (d, i) => x(data[i].name))
    .attr('width', x.bandwidth())
    .attr('height', d => y(d[0]) - y(d[1]))
    .attr('y', d => y(d[1]))
    .attr('opacity', 0.7)

  // 製作 yAxis
  svg.append('g')
  	.attr('class', 'y-axis')
    .call(yAxis);
	
  svg.append('g')
    .attr('class', 'x-axis')
  	.attr('transform', `translate(0, ${height})`)
  	.call(xAxis)
    .selectAll('text') // 选择所有 x 轴上的文字标签
  	.style('text-anchor', 'end') // 设置文字锚点为起始位置
  	.style('font-size', '0.5em') // 设置文字字体大小
  	.attr('dx', '-0.5em') // 增加一些水平偏移以让文字不重叠
  	.attr('dy', '-1.5em') // 垂直偏移，以调整文字的位置
  	.attr('transform', 'rotate(270)'); // 旋转文字
  
  // Create Legend
  const legend = svg.append('g')
    .attr('class', 'legend')
    .attr('transform', `translate(${-20}, ${-60})`); // 适当调整位置

  legend.selectAll('circle')
    .data(legendData)
    .enter()
  	.append('g')
  	.attr('class', d => `group-${d.key}`) 
    .append('circle')
    .attr('cx', (d, i) => i * (rectSize + rectSpacing) + rectSize / 2) // 适当调整水平位置
    .attr('cy', 30) // 适当调整垂直位置
    .attr('r', rectSize / 2) // 半径为矩形大小的一半，以保持相同的大小
    .attr('fill', d => d.color) // 使用数据中定义的颜色
		.on('mouseover', function (d) {
    		const matchingItem = legendData.find(item => item.color === this.getAttribute('fill'));
				const selectedCategory = matchingItem.key
    		
        // 在悬停时更改选定类别对应的堆叠柱状图透明度为 1（高亮）
        svg.selectAll(`.group-${selectedCategory} rect`)
          .attr('opacity', 1);

        // 同时，更改其他非选定类别的堆叠柱状图透明度为 0.2（变淡）
        keys.filter(key => key !== selectedCategory).forEach(category => {
          svg.selectAll(`.group-${category} rect`)
            .attr('opacity', 0.2);
        });
    })
    .on('mouseout', function (d) {
        // 在悬停结束时恢复所有堆叠柱状图的透明度为 0.8
        svg.selectAll('rect').attr('opacity', 0.7);
    });
  
  legend.selectAll('text')
    .data(legendData)
    .enter()
    .append('text')
    .attr('x', (d, i) => i * (rectSize + rectSpacing) + rectSize / 2 + 22) // 适当调整水平位置
    .attr('y', textX)
    .attr('alignment-baseline', 'middle')
  	.attr('dominant-baseline', 'hanging') // 设置文本基线为顶部
  	.style('font-size', '1.2em') // 设置文字字体大小
    .text(d => d.key);
  
 };
	
  var btn = document.getElementById('btn');
  btn.addEventListener('click', () => {
      data_process_and_draw();
  });

	var Methodology = "Overall";
  var X = document.getElementById('X');
  X.addEventListener('change', function(e){
    Methodology = e.target.value.toString();
  });

  var Way = "descending";
  var Y = document.getElementById('Y');
  Y.addEventListener('change', function(e){
    Way = e.target.value.toString();
  });


function data_process_and_draw(){
  csv('university.csv')
    .then(data => {
      data = data.filter(data => data['scores_overall'] != 'n/a');
      data.forEach(d => {	
          d['Teaching'] = +d['scores_teaching'] * 0.295 ;
          d['Research'] = +d['scores_research'] * 0.29 ;
          d['Citations'] = +d['scores_citations'] * 0.3 ;
          d['Industry_income'] = +d['scores_industry_income'] * 0.04 ;
          d['International_outlook'] = +d['scores_international_outlook'] * 0.075;
          // score_overall 透過各加權指標相加	
          d['Overall'] = d['International_outlook'] + d['Industry_income'] + d['Citations'] + d['Research'] + d['Teaching']
      });
		sort_data(data);
    d3.select('svg').remove();
    render(data);
  });
}

function sort_data(data){
  data.sort(function (a, b) {
  	return a[Methodology] - b[Methodology];
  });
  if (Way==="descending"){
    data.reverse()
  }
}

function swap_keys(){
  if(Methodology != "Overall"){
		var v1 = keys.indexOf(Methodology);
  	[keys[v1], keys[0]] = [keys[0], keys[v1]]; 
  }
}

data_process_and_draw()


===================================

  // Key Color
  var colorScale = d3.scaleOrdinal()
  									 .domain(keys)
  									 .range(['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd']); 