from pyecharts.charts import Gauge,Pie,Line,Bar
from pyecharts.render import make_snapshot
from snapshot_selenium import snapshot
from pyecharts import options as opts

def charts(datalist,charttype,pngpath):
    try:
        img = None
        if charttype == 1: #仪表盘
            img = Gauge()
            img.add("知产价值评估",[("", datalist[0]["value"])], axisline_opts=opts.AxisLineOpts(
                    linestyle_opts=opts.LineStyleOpts(
                        color=[(0.3, "#67e0e3"), (0.7, "#37a2da"), (1, "#fd666d")], width=30
                    )),label_opts=opts.LabelOpts(formatter="{value}"))
        elif charttype == 2:#饼状图
            img = Pie()
            valuelist = []
            for list in datalist:
                valuelist.append((list["key"],list["value"]))
            img.add("", valuelist, label_opts=opts.LabelOpts(formatter="{b}: {c}"))
        elif charttype ==3:#折线图
            img = Line()
            keylist = []
            valuelist = []
            for list in datalist:
                keylist.append(list["key"])
                valuelist.append(list["value"])
            img.add_xaxis(keylist)
            img.add_yaxis("",valuelist,color= "#1E90FF")
        elif charttype ==4:#柱状图
            img = Bar()
            keylist = []
            valuelist = []
            for list in datalist:
                keylist.append(list["key"])
                valuelist.append(list["value"])
            img.add_xaxis(keylist)
            img.add_yaxis("",valuelist,color= "#1E90FF")
        if img:
            make_snapshot(snapshot, img.render(), pngpath)
            return  True
        else:
            return False
    except Exception as e1:
        print(e1)
        return  False


# 下面一句的作用1是：运行本程序文件时执行什么操作
if __name__ == "__main__":
    data1 = [{"key":"价值评价","value":55.9}]
    charts(data1,1,"1.png")
    name = ["2014", "2015", "2016", "2017", "2018", "2019"]
    value = [100, 300, 250, 90, 150, 50]
    data2 = [{"key":"运行","value":100},{"key":"2015","value":300},{"key":"2016","value":250},{"key":"2017","value":150},
             {"key":"2018","value":200},{"key":"2019","value":90}]
    charts(data2,2,"2.png")
    charts(data2,3,"3.png")
    charts(data2,4,"4.png")
    charts(data2,5,"5.png")
    print("over")


