import Taro from '@tarojs/taro'
import { View, Canvas } from '@tarojs/components'

import classNames from 'classnames'
import PropTypes, { InferProps } from 'prop-types'
import CtsComponent from '../../common/component'
import { CtsCircleProps, CtsCircleState } from 'types/circle'


/**
 * 圆形步骤条组件
 */
export default class CtsCircle extends CtsComponent<CtsCircleProps, CtsCircleState> {
	// static options = {
	//   addGlobalClass: true
	// }

	public static defaultProps: CtsCircleProps
	public static propTypes: InferProps<CtsCircleProps>

	public constructor(props: CtsCircleProps) {
		super(props)
		this.state = {
			ctx: null,
			rate: 0,
			imgSrc: ''
		}
	}

	public componentWillReceiveProps(props: CtsCircleProps): void {
		console.log('circle componentWillReceiveProps', props)

		// 初始化数据
		this.initCircle(props)
	}

	public componentDidMount(): void {
		console.log('circle componentDidMount', this.props)

		// 初始化数据
		this.initCircle(this.props)
	}

	// 初始化数据
	initCircle(props) {
		let { size, rate, width } = props
		let ctx = Taro.createCanvasContext('canvas', this)

		if (!(rate > 0)) {
			rate = 0
		}

		this.setState({
			rate
		}, () => {
			ctx.clearRect(0, 0, size * 2, size * 2)

			// 创建圆环背景
			this.drawCircleBg(ctx, size, width, rate)
		})
	}

	// 创建圆环背景（id：canvas组件的唯一标识符canvasId，x：canvas绘制图形的半径，w：canvas绘制圆环的宽度）
	private drawCircleBg(ctx, x, w, r) {
		console.log('创建圆环背景')

		// 设置圆环外面盒子大小，宽高都等于圆环半径
		// 使用Taro.createCanvasContext获取绘图上下文ctx绘制背景圆环
		// let ctx = Taro.createCanvasContext(id, this)

		// ctx.rect(10, 10, 100, 30)
		// ctx.setFillStyle('yellow')
		// ctx.fill()
		// ctx.draw()
		const that = this
		ctx.setLineWidth(w) // 设置线条的宽度
		ctx.setStrokeStyle('#f8f8f8') // 设置描边颜色
		ctx.setLineCap('round') // 设置线条的端点样式
		ctx.beginPath() // 开始一个新的路径

		// 设置一个原点（x，y），半径为r的圆的路径到当前路径，此处x=y=r
		ctx.arc(x, x, x - w, 0, 2 * Math.PI, false) // 创建一条弧线
		ctx.stroke() // 对当前路径进行描边

		if (r) {
			ctx.draw()
			this.drawCircle(ctx, x, w, r)
		} else {
			// 将之前在绘图上下文中的描述（路径，变形，样式）画在canvas中
			console.log('半径为0时直接生成图片')
			ctx.draw(false, setTimeout(() => {
				
				Taro.canvasToTempFilePath({
					x: 0,
					y: 0,
					canvasId: 'canvas',
					success: function (res) {
						console.log('canvasToTempFilePath', res)
						that.getImage(res)
					},
					fail: function (res) {
						console.log(res)
					}
				}, this.$scope)
			}, 50)
			)
		}
	}

	// 创建圆环显示
	private drawCircle(ctx, x, w, rate) {
		console.log('创建圆环显示')
		// 使用Taro.createContext获取绘图上下文context绘制彩色进度条圆环
		// let ctx = Taro.createCanvasContext(id, this)
		const that = this
		// 设置渐变
		let gradient = ctx.createLinearGradient(x, 0, x, 2 * x) // 创建一个线性的渐变颜色
		gradient.addColorStop(0, Taro['common'].colorGradient1) // 添加颜色的渐变点。小于最小stop的color来渲染，大于最大stop的部分会按最大stop的color来渲染
		gradient.addColorStop(1.0, Taro['common'].colorGradient2)
		ctx.setLineWidth(w)
		ctx.setStrokeStyle(gradient)
		ctx.setLineCap('round')
		ctx.beginPath() // 开始一个新的路径

		// step从0到2为一周
		ctx.arc(x, x, x - w, -Math.PI / 2, rate / 50 * Math.PI - Math.PI / 2, false)
		ctx.stroke() // 对当前路径进行描边

		ctx.draw(true, setTimeout(() => {
			Taro.canvasToTempFilePath({
				x: 0,
				y: 0,
				canvasId: 'canvas',
				success(res) {
					console.log('canvasToTempFilePath', res)
					that.getImage(res)
				},
				fail(res) {
					console.log(res)
				}
			}, this.$scope)
		}, 50)
		)
	}

	getImage(data) {
		let tempFilePath = data.tempFilePath
		console.log('getImage', tempFilePath)
		this.setState({
			imgSrc: tempFilePath
		})
	}

	// 圆环添加动画
	// private addAnimate(ctx, props) {
	//   const { size } = props
	//   const { rate } = this.state

	//   let count = 0 // 计数器，开始位置
	//   let maxCount = 50 // 绘制一个圆环所需的步骤
	//   let interval = setInterval(() => {
	//     count++
	//     if (count >= maxCount) {
	//       clearInterval(interval)
	//       return
	//     }
	//     console.log((count / maxCount) * rate)

	//     if (Boolean((count / maxCount) * rate)) { 
	//       this.drawCircle(ctx, size, 6, (count / maxCount) * rate)
	//     }
	//   }, 5)
	// }

	public render(): JSX.Element {
		let { className, size } = this.props
		let { imgSrc } = this.state
		size *= 2

		return (
			<View className={classNames('cts-circle', className)} style={{ width: size + 'px', height: size + 'px' }}>
				{
					imgSrc &&
					<Image src={imgSrc} className='canvas-img' style={{ width: size + 'px', height: size + 'px' }}></Image>
				}

				<Canvas className='circle_draw' canvasId='canvas' style={{ width: size + 'px', height: size + 'px' }}></Canvas>
				<View className='cts-circle-text'>{this.props.children}</View>
			</View>
		)
	}
}

CtsCircle.defaultProps = {
	size: 50,
	rate: 0,
	width: 6
}

CtsCircle.propTypes = {
	size: PropTypes.number,
	rate: PropTypes.number,
	width: PropTypes.number
}