<template>
    <PageHeader :title="title">
        <template #action>
            <div style="text-align: left;">
                <Select v-model="ReC.project" style="width:200px" placeholder="项目" @on-change="getiterations">
                    <Option v-for="item in projects" :value="item.key" :key="item.key">{{
        item.name }}</Option>
                </Select>
                <Select v-model="ReC.iteration" style="width:200px;margin-left: 10px;" placeholder="迭代"
                    @on-change="getReportInfo">
                    <Option v-for="item in iterations" :value="item.key" :key="item.key">{{ item.name }}</Option>
                </Select>
                <Button type="primary" @click="breforesend" style="width:100px;margin-left: 10px;">发送邮件</Button>
            </div>
        </template>
    </PageHeader>
    <Card v-if="report">
        <template #extra>
            <Icon v-if="!edit" type="md-create" @click="edit = !edit" size="20" color="#2b85e4" />
            <Icon v-if="edit" type="md-checkmark-circle-outline" @click="edit = !edit" size="20" color="#2b85e4" />
        </template>
        <div style="margin-top: 8px;" id="reportBox">
            <h2 style="text-align: center;">{{ info.project + "-" + info.sprint + "测试报告" }}</h2>
            <h4 style="text-align: center;">{{ myname }}</h4>
            <Button shape="circle" style="margin-top: 10px;margin-bottom: 10px;" type="primary">测试结论</Button>
            <p>
                &nbsp; &nbsp;
                <Paragraph v-if="edit" v-model="testResult" editable />
                <span v-if="!edit">{{ testResult }}</span>
            </p>
            <div style="background-color: #dcdee2;">
                <P>
                    <span>用例总数：{{ mycase.length }};</span>
                    <span>用例密度：{{ story ? ((mycase.length) / (story.length)).toFixed(2) : 0 }};</span>
                    <span>覆盖率：</span>
                    <span v-if="fugailu == 100" style="color: #19be6b;">{{ fugailu }}%</span>
                    <span v-else style="color: #ed4014;">{{ fugailu }}%</span>
                </P>
                <span v-for="item in story">
                    <span>{{ item.summary }}:{{ item.case.length }};&nbsp; &nbsp; </span>
                </span>

                <P>
                    <span>bug总数：{{ bug.length }};</span>
                    <span>未关闭bug数：</span>
                    <span v-if="bug.filter(ele => { return ele.statusId != getStatuSuccessId() }).length == 0"
                        style="color: #19be6b;">{{
        bug.filter(ele => { return ele.statusId != getStatuSuccessId() }).length }}</span>
                    <span v-else style="color: #ed4014;">{{ bug.filter(ele => {
        return ele.statusId != getStatuSuccessId()
    }).length
                        }}</span>
                </P>
            </div>
            <Button shape="circle" style="margin-top: 10px;margin-bottom: 10px;" type="primary">风险</Button>
            <p>
                &nbsp; &nbsp;
                <Paragraph v-if="edit" v-model="fengxxian" editable />
                <span v-if="!edit">{{ fengxxian }}</span>
            </p>
            <Button shape="circle" style="margin-top: 10px;margin-bottom: 10px;" type="primary">测试计划资源情况</Button>
            <Table :columns="storycolumns" :data="story">
                <template #summary="{ row, index }">
                    <a :href='"http://jira.galaxy-immi.com/browse/" + row.key'>
                        <u>{{ row.summary }}</u>
                    </a>
                </template>
                <template #chan="{ row, index }">
                    <p>
                        {{ filterPeopleString('chan', row.peoples) }}
                    </p>
                </template>
                <template #qian="{ row, index }">
                    <p>
                        {{ filterPeopleString('qian', row.peoples) }}
                    </p>
                </template>
                <template #hou="{ row, index }">
                    <p>
                        {{ filterPeopleString('hou', row.peoples) }}
                    </p>
                </template>
                <template #test="{ row, index }">
                    <p>
                        {{ filterPeopleString('test', row.peoples) }}
                    </p>
                </template>
                <template #start="{ row, index }">
                    <p v-if="!edit">
                        {{ row.start }}
                    </p>
                    <Paragraph v-else v-model="row.start" editable />
                </template>
                <template #end="{ row, index }">
                    <p v-if="!edit">
                        {{ row.end }}
                    </p>
                    <Paragraph v-else v-model="row.end" editable />
                </template>
                <template v-if="edit" #action="{ row, index }">
                    <Icon type="ios-remove-circle" style="color: crimson;" @click="this.story.splice(index, 1)"
                        size="15" />
                </template>
            </Table>
            <Button shape="circle" style="margin-top: 10px;margin-bottom: 10px;" type="primary">测试用例</Button>
            <div>
                <div v-for="item in story">
                    <Button type="info" style="width: 100%;text-align: left;">
                        {{ item.summary }}
                    </Button>
                    <Table :columns="casecolumns" :data="item.case.map(ele => { return { key: ele } })">
                        <template #summary="{ row, index }">
                            <a v-if="searchCaseBykey(row.key)" :href='"http://jira.galaxy-immi.com/browse/" + row.key'>
                                <u>{{ searchCaseBykey(row.key).summary }}</u>
                            </a>
                            <p v-else style="color: #ed4014;">面板未找到相关用例，请联系jira人员配置</p>
                        </template>
                        <template #status="{ row, index }">
                            <p v-if="searchCaseBykey(row.key)">
                                {{ statusMap[searchCaseBykey(row.key).statusId] }}
                            </p>
                        </template>
                        <template v-if="edit" #action="{ row, index }">
                            <Icon type="ios-remove-circle" style="color: crimson;"
                                @click="item.case.splice(index, 1); rmcase(row.key)" size="15" />
                        </template>
                    </Table>
                </div>
            </div>
            <!-- <Collapse simple v-model="cShow">
                <Panel v-for="item in story" :name="item.key">
                    
                    <template #content>
                        
                    </template>
                </Panel>
            </Collapse> -->
            <Button shape="circle" style="margin-top: 10px;margin-bottom: 10px;" type="primary">bug记录</Button>
            <Table :columns="bugcolumns" :data="bug">
                <template #summary="{ row, index }">
                    <a :href='"http://jira.galaxy-immi.com/browse/" + row.key'>
                        <u>{{ row.summary }}</u>
                    </a>
                </template>
                <template #create="{ row, index }">
                    <p>
                        {{ row.extraFields[1].html }}
                    </p>
                </template>
                <template #priority="{ row, index }">
                    <p>
                        {{ priorityMap[row.priorityId] }}
                    </p>
                </template>
                <template #status="{ row, index }">
                    <p>
                        {{ statusMap[row.statusId] }}
                    </p>
                </template>
                <template #people="{ row, index }">
                    <p>
                        {{ row.assigneeName }}
                    </p>
                </template>
                <template v-if="edit" #action="{ row, index }">
                    <Icon type="ios-remove-circle" style="color: crimson;" @click="this.bug.splice(index, 1)"
                        size="15" />
                </template>
            </Table>
        </div>
        <div id="biao" style="margin-top: 10px;">
            <Row>
                <Col :span="12">
                <v-chart :option="bug_create_column" style="height: 300px"></v-chart></Col>
                <Col justify="center" :span="12">
                <v-chart :option="bug_p_column" style="height: 300px"></v-chart></Col>
            </Row>
            <Row>
                <!-- <Col justify="center" :span="12">
                <v-chart :option="case_s_column" style="height: 300px"></v-chart></Col> -->
                <Col :span="12">
                <v-chart :option="bug_user_column" style="height: 300px"></v-chart></Col>
            </Row>
        </div>
    </Card>
    <Space wrap>
        <Modal title="选择收件人" v-model="modlShow" class-name="vertical-center-modal" @on-cancel="closeShow()">
            <Select v-model="sendto" multiple style="width:260px">
                <Option v-for="item in emailList" :value="item.address" :key="item.id">{{ item.name }}</Option>
            </Select>
            <template #footer>
                <Button @click="closeShow()">取消</Button>
                <Button type="primary" @click="send()">确认</Button>
            </template>
        </Modal>
    </Space>
</template>

<script>
import html2canvas from "html2canvas";
export default {
    props: ['isCollapsed'],
    data() {
        return {
            modlShow: false,
            sendto: [],
            emailList: [],
            bug_p_column: {
                title: {
                    text: 'bug优先级占比',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left'
                },
                series: [
                    {
                        name: 'Access From',
                        type: 'pie',
                        radius: '50%',
                        data: [
                        ],
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            },
            mycase: [],
            report: false,
            case_s_column: {
                title: {
                    text: '用例状态占比',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left'
                },
                series: [
                    {
                        name: 'Access From',
                        type: 'pie',
                        radius: '50%',
                        data: [
                        ],
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            },
            bug_create_column: {
                title: {
                    text: 'bug产出趋势',
                    left: 'center'
                },
                xAxis: {
                    type: 'category',
                    data: []
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        data: [],
                        type: 'line'
                    }
                ]
            },
            bug_user_column: {
                title: {
                    text: '开发bug分布',
                    left: 'center'
                },
                xAxis: {

                    axisLabel: { interval: 0, },

                    type: 'category',
                    data: []
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        data: [],
                        type: 'bar'
                    }
                ]
            },
            cShow: [],
            p1option: [],
            page_id: 17,
            title: "测试报告",
            edit: false,
            projects: [],
            iterations: [],
            ReC: {
                project: null,
                iteration: null
            },
            testResult: '所有测试用例均已完成，所有bug均已修复，测试通过',
            fengxxian: "无",
            myname: null,
            bug: [],
            case: [],
            people: [],
            story: [],
            storycolumns: [
                {
                    title: '需求',
                    slot: 'summary'
                },
                {
                    title: '产品',
                    slot: 'chan'
                },
                {
                    title: '前端',
                    slot: 'qian'
                },
                {
                    title: '后端',
                    slot: 'hou'
                },
                {
                    title: '测试',
                    slot: 'test'
                },
                {
                    title: '开始时间',
                    slot: 'start'
                },
                {
                    title: '结束时间',
                    slot: 'end'
                }
            ],
            casecolumns: [
                {
                    title: '用例名',
                    slot: 'summary'
                },
                {
                    title: '状态',
                    slot: 'status'
                }
            ],
            bugcolumns: [
                {
                    title: 'BUG',
                    slot: 'summary'
                },
                {
                    title: '提出时间',
                    slot: 'create'
                },
                {
                    title: '优先级',
                    slot: 'priority'
                },
                {
                    title: '状态',
                    slot: 'status'
                },
                {
                    title: '修复人',
                    slot: 'people'
                }
            ],
            info: {
                project: null,
                sprint: null
            },
            statusMap: {},
            priorityMap: {},
            typeMap: {},
            caseCount: 0,
            fugailu: 0
        }
    },
    methods: {
        breforesend() {
            if (!this.report) return this.$Message.error("请先完善报告信息")
            this.getallEmail();
            this.modlShow = true;
        },
        searchCaseBykey(key) {
            const index = this.mycase.findIndex(ele => { return ele.key == key })
            return index == -1 ? null : this.mycase[index]
        },
        rmcase(key) {
            const index = this.mycase.findIndex(ele => ele.key == key)
            index != -1 && this.mycase.splice(index, 1)
        },
        filterPeopleString(type, people) {
            var result = ''
            people.forEach(ele => {
                if (this.people[type].indexOf(ele) != -1) { result = result + " " + ele }
            })
            return result
        },
        getprojects() {
            this.$request('get', 'tool/testport/getproject', null, this, (data) => { this.projects = data.data; this.ReC.iteration = null })
        },
        getiterations(project) {
            this.$request('get', 'tool/testport/iteration/' + project, null, this, (data) => { this.iterations = data.data })
        }, getReportInfo() {
            if (!this.ReC.iteration) return
            this.$request('get', 'tool/testport/reportinfo', this.ReC, this, (data) => {
                this.bug = data.data.bug
                this.case = data.data.testcase
                this.people = data.data.people
                this.story = data.data.story
                this.info.project = data.data.project
                this.info.sprint = data.data.sprint
                this.statusMap = data.data.statusMap
                this.priorityMap = data.data.priorityMap
                this.typeMap = data.data.typeMap
                this.render()
            })
        },
        getStatuSuccessId() {
            for (var k in this.statusMap) {
                if (this.statusMap[k] == '完成' || this.statusMap[k] == '已完成') return k
            }
        },
        render() {
            this.report = true
        },
        async send() {
            if (!this.report) return
            this.edit = false
            const html = document.getElementById("reportBox").innerHTML
            var stylestart = '<head><style type="text/css">'
            var styleend = '</style></head>'
            const cssBlock = document.styleSheets
            for (var i of cssBlock) {
                for (var j of i.rules) {
                    if (j.selectorText == ".ivu-table") {
                        stylestart = stylestart + ".ivu-table {width: inherit;max-width: 100%;overflow: hidden;color: rgb(81, 90, 110);font-size: 14px;background-color: rgb(255, 255, 255);box-sizing: border-box;}"
                    }
                    else { stylestart = stylestart + j.cssText }
                }
            }
            const c = (stylestart + styleend + html).replace(/style="width(.*?)"/gm, 'style="width:100%"')
            // const info = '<div style="display:flex"><div id="c1" style="width: 50%;height: 300px;"></div><div id="c2" style="width: 50%;height: 300px;"></div></div><div style="display:flex"><div id="c3" style="width: 50%;height: 300px;"></div><div id="c4" style="width: 50%;height: 300px;"></div></div>'
            // const cjs1 = `var chartDom1 = document.getElementById('c1');var myChart1 = echarts.init(chartDom1);myChart1.setOption(${JSON.stringify(this.bug_create_column)});`
            // const cjs2 = `var chartDom2 = document.getElementById('c2');var myChart2 = echarts.init(chartDom2);myChart2.setOption(${JSON.stringify(this.bug_p_column)});`
            // const cjs3 = `var chartDom3 = document.getElementById('c3');var myChart3 = echarts.init(chartDom3);myChart3.setOption(${JSON.stringify(this.case_s_column)});`
            // const cjs4 = `var chartDom4 = document.getElementById('c4');var myChart4 = echarts.init(chartDom4);myChart4.setOption(${JSON.stringify(this.bug_user_column)});`
            // const result = c + info + '<' + 'script type="text/javascript" src="https://cdn.staticfile.org/echarts/5.5.0/echarts.min.js"></' + 'script>' + "<" + 'script type="text/javascript">' + cjs1 + cjs2 + cjs3 + cjs4 + "<" + "/script>"
            var htmlDom = document.getElementById("biao")
            html2canvas(htmlDom, {
                useCORS: true,
                width: window.screen.availWidth,
                height: window.screen.availHeight,
                windowwidth: document.body.scrollWidth,
                windowHeight: document.body.scrollHeight,
                x: 0,
                y: window.pageYOffset
            }).then((canvas) => {
                const m = `<img src='${canvas.toDataURL("image/png")}'/>`
                const result = c + m
                const sub = this.info.project + "-" + this.info.sprint + "测试报告"
                console.info(result)
                this.$request("post", "/tool/testport/sendport", { to: this.sendto, subject: sub, contents: result }, this, () => { this.closeShow() })
            });
        },
        getallEmail() {
            this.$request("get", "/tool/testport/emailuserlist", null, this, (data) => { this.emailList = data.data })
        },
        closeShow() {
            this.sendto = []
            this.modlShow = false
        }
    },
    watch: {
        edit(value) {
            const a = {
                title: ' ',
                slot: 'action'
            }
            if (value) {
                this.storycolumns.push(a)
                this.bugcolumns.push(a)
                this.casecolumns.push(a)
            } else {
                const index1 = this.storycolumns.findIndex(ele => { return ele.slot == 'action' })
                const index2 = this.bugcolumns.findIndex(ele => { return ele.slot == 'action' })
                const index3 = this.casecolumns.findIndex(ele => { return ele.slot == 'action' })
                index1 == -1 || this.storycolumns.splice(index1, 1)
                index2 == -1 || this.bugcolumns.splice(index2, 1)
                index3 == -1 || this.casecolumns.splice(index3, 1)
            }
        },
        bug: {
            handler(value) {
                this.bug_p_column.series[0].data = []
                this.bug_create_column.xAxis.data = []
                this.bug_create_column.series[0].data = []
                this.bug_user_column.xAxis.data = []
                this.bug_user_column.series[0].data = []
                if (value) {
                    var pinfo = {}
                    var dateinfo = {}
                    var bugUser = {}
                    value.forEach(ele => {
                        ele.priorityId in pinfo ? pinfo[ele.priorityId]++ : pinfo[ele.priorityId] = 1
                        // let date = ele.extraFields[1].html.split(' ')[0] || ''
                        const index = ele.extraFields.findIndex(ele => { return ele.id == "created" })
                        let date = index != -1 ? ele.extraFields[index].html.split(' ')[0] : 0
                        date in dateinfo ? dateinfo[date]++ : dateinfo[date] = 1
                        ele.assigneeName in bugUser ? bugUser[ele.assigneeName]++ : bugUser[ele.assigneeName] = 1
                    })
                    for (var i in pinfo) {
                        this.bug_p_column.series[0].data.push({ value: pinfo[i], name: this.priorityMap[i] })
                    }

                    for (var i in dateinfo) {
                        this.bug_create_column.xAxis.data.push(i)
                        this.bug_create_column.series[0].data.push(dateinfo[i])
                    }
                    for (var i = 0; i < this.bug_create_column.xAxis.data.length; i++) {
                        for (var j = i + 1; j < this.bug_create_column.xAxis.data.length; j++) {
                            if (this.bug_create_column.xAxis.data[i] > this.bug_create_column.xAxis.data[j]) {
                                const a = this.bug_create_column.xAxis.data[i]
                                const b = this.bug_create_column.series[0].data[i]
                                this.bug_create_column.xAxis.data[i] = this.bug_create_column.xAxis.data[j]
                                this.bug_create_column.xAxis.data[j] = a
                                this.bug_create_column.series[0].data[i] = this.bug_create_column.series[0].data[j]
                                this.bug_create_column.series[0].data[j] = b
                            }
                        }
                    }

                    for (var i in bugUser) {
                        this.bug_user_column.xAxis.data.push(i)
                        this.bug_user_column.series[0].data.push(bugUser[i])
                    }
                }
            }, deep: true
        },
        story: {
            handler(value) {
                if (value) {
                    this.mycase = []
                    var a = 0
                    var b = 0
                    this.cShow = value.map(ele => { return ele.key });
                    value.forEach(ele => {
                        if (ele.case.length > 0) {
                            b += 1
                        };
                        a += 1
                    })
                    value.forEach(ele => {
                        const index = ele.extraFields.findIndex(item => { return item.id == "created" })
                        ele.start = index != -1 ? ele.extraFields[index].html.split(" ")[0] : ''
                        ele.end = new Date().toLocaleDateString()
                        this.case.forEach(each => {
                            if (ele.case.indexOf(each.key) != -1) {
                                this.mycase.push(each)
                            }
                        })
                    })
                    this.fugailu = a ? ((b / a) * 100).toFixed(2) : 0
                }
            },
            deep: true
        },
        mycase: {
            handler(value) {
                this.case_s_column.series[0].data = []
                if (value) {
                    var info = {}
                    value.forEach(ele => {
                        ele.statusId in info ? info[ele.statusId]++ : info[ele.statusId] = 1
                    })
                    for (var i in info) {
                        this.case_s_column.series[0].data.push({ value: info[i], name: this.statusMap[i] })
                    }
                }
            },
            deep: true
        }
    },
    created() {
        this.getprojects()
        this.myname = JSON.parse(localStorage.getItem("userinfo")).name
    },
    mounted() {
    }
};
</script>

<style>
.chart {
    height: 100vh;
}
</style>