import React, {useMemo} from 'react';

const labelWidth = 60;

const flatRules = {
  // 给1 展示100%
  // 给1.0000 展示100.0%
  // 给0.9  展示90%
  // 给0.90000 展示90.0%
  "strange": val => {
    val = val + "";
    let valArr = val.split("");
    // console.log("val1", val);
    for (let n = 2; n > 0; n--) { 
      let dotIndex = valArr.findIndex(i => i === ".");
      if (dotIndex > 0) {
        if (dotIndex === valArr.length - 1) {
          valArr.push("0")
        }
        valArr[dotIndex] = valArr.splice(dotIndex + 1, 1, valArr[dotIndex])[0]
      } else { 
        valArr.push("0")
      }
    }
    let dotIndex = valArr.findIndex(i => i === ".");
    if (dotIndex > 0) { 
      while (valArr[0] === "0" && valArr[1] !== ".") { 
        valArr = valArr.splice(1, valArr.length)
      }
    }
    val = valArr.join("");
    // console.log("val2", val);
    return val + "%"
  }
};
function TableProgress(props) {
  const {percent, toFixed = 1, rule} = props;

  const percentVal = useMemo(() => {
    if (rule && flatRules[rule]) return flatRules[rule](percent);
    if (toFixed === false) return percent * 100 + "%";
    return (percent * 100).toFixed(toFixed) + "%"
  }, [percent, toFixed])

  const width = useMemo(() => {
    if (percent > 1) percent = 1;
    if (toFixed === false) return percent * 100;
    return (percent * 100).toFixed(toFixed)
  }, [percent, toFixed])
  return (
    <div className='table-progress'>
      <div className='table-progress-label'>{percentVal}</div>
      <div className='table-progress-bar'>
        <div className='table-progress-bar-content'></div>
      </div>
      <style jsx>{`
        .table-progress-bar{
          margin-right: ${labelWidth}px;
          padding: 5px 0;
        }
        .table-progress-bar-content{
          height: 12px;
          background: rgba(255,255,255,0.16);
        }
        .table-progress-bar-content:before{
          content: '';
          display: block;
          height: 100%;
          background: #28A3FF;
          width: ${width}%;
        }
        .table-progress-label{
          width: ${labelWidth}px;
          float: right;
          text-align: center;
        }
      `}</style>
    </div>
  );
}

export default TableProgress;