<template>
    <PageHeader :title="title">
        <template #action>
            <div style="text-align: left;">
                <Select v-if="pagestatus == 0" filterable v-model="ReC.project" style="width:200px" placeholder="项目"
                    @on-change="getview">
                    <Option v-for="item in projects" :value="item.id" :key="item.id">{{
                        item.name }}</Option>
                </Select>
                <Select v-if="pagestatus == 0" v-model="ReC.view" style="width:200px;margin-left: 10px;"
                    placeholder="面板" @on-change="getiterations">
                    <Option v-for="item in views" :value="item.id" :key="item.id">{{ item.name }}</Option>
                </Select>
                <Select v-if="pagestatus == 0" 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" v-if="(!reporttype) || (reporttype && audit_status == 1 && self)"
                    @click="breforesend" style="width:100px;margin-left: 10px;">发送邮件</Button>
                <Button type="primary" v-if="pagestatus == 0 || pagestatus == 1" @click="breforerunjenkins"
                    style="width:130px;margin-left: 10px;">回归脚本运行</Button>
            </div>
            <div style="text-align: left;margin-top: 10px;">
                <DatePicker v-model="receive_time" type="date" :options="options1" placeholder="邮件收件时间"
                    style="width: 200px" />

                <Select v-model="mail_id" style="width:200px;margin-left: 10px;" placeholder="请选择回复邮件">
                    <Option v-for="item in receive_mails" :value="item.id">
                        <slot>
                            <p style="font-size: 15px;font-weight: bold">{{ item.sub }}</p>
                            <div
                                style="display:flex;justify-content: space-between;margin-right: 8px;margin-left: 8px;margin-top: 3px;">
                                <div style="">{{ item.from }}</div>
                                <div style="color: #808695;">{{ item.receive_time }}</div>
                            </div>
                        </slot>
                    </Option>

                </Select>

            </div>
        </template>
        <template #content>
            <div></div>
        </template>
        <template #extra style="text-align: right;">
            <CheckboxGroup v-if="pagestatus == 0 || pagestatus == 1" v-model="plugs">
                <span style="font-size: 16px;">插件：</span>
                <Checkbox label="自动化运行结果" border></Checkbox>
                <Checkbox label="左移-接口测试" border></Checkbox>
            </CheckboxGroup>
        </template>
    </PageHeader>
    <Collapse v-if="pagestatus == 0 || pagestatus == 1" v-model="defaultvalue" accordion simple>
        <Panel name="1">
            jenkins最新运行结果
            <template #content>
                <Table :columns="jenkins_columns" :data="jenkis_data">
                    <template #action="{ row, index }">
                        <div fix v-if="row.running">
                            <Icon type="md-ionic" size=18 class="demo-spin-icon-load"></Icon>
                            <div>运行中</div>
                        </div>
                        <div v-if="!row.running">
                            <Icon v-if="row.result == 'SUCCESS'" type="ios-checkmark-circle-outline" size=18
                                style="color: #19be6b;"></Icon>
                            <div v-if="row.result == 'SUCCESS'">已完成</div>
                            <Icon v-if="row.result == 'ABORTED'" type="md-close-circle" size=18 style="color: #c5c8ce;">
                            </Icon>
                            <div v-if="row.result == 'ABORTED'">已取消</div>
                            <Icon v-if="row.result == 'FAILURE'" type="ios-close-circle-outline" size=18
                                style="color: #ed4014;"></Icon>
                            <div v-if="row.result == 'FAILURE'">失败</div>
                        </div>
                    </template>
                </Table>
            </template>
        </Panel>
    </Collapse>
    <Card v-if="report">
        <template v-if="pagestatus == 0 || pagestatus == 1" #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" />
            <Button style="margin-left: 20px;" type="primary" ghost @click="this.stagingshow = true">保存</Button>
        </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" id="jielun"></span>
            </p>
            <br />
            <div style="background-color: #dcdee2;margin-left: 1em;">
                <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>
                <p>
                    <span v-for="item in story">
                        <span>{{ item.summary }}:</span><span :style="colorstyle(item.case ? item.case.length : 0)"
                            style="margin-right: 3px;">{{ item.case ? item.case.length : 0
                            }}</span><span>个用例；</span>
                    </span>
                </p>
                <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 ref="stroy" :columns="storycolumns" :data="story">
                <template #summary="{ row, index }">
                    <a target="_blank" :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>
            <div v-if="edit" style="margin: 5px;"><Button @click="changeStoryList()">删除未选中</Button></div>
            <template v-if="plugs.includes('左移-接口测试')">
                <Button shape="circle" style="margin-top: 10px;margin-bottom: 10px;" type="primary">左移-接口测试</Button>
                <br>
                <template v-if="(apitestinfos.length == 1 && !Object.keys(apitestinfos[0]).length) || edit"
                    v-for="(api_url, index) in api_urls">
                    <Input v-model="api_urls[index]" @on-blur="renderapihtml(api_url, index)"
                        placeholder="请输入apifox分享的报告链接" style="width: 300px" />
                    <Icon v-if="api_urls.length > 1" type="ios-remove-circle" style="color: crimson;"
                        @click="this.api_urls.splice(index, 1); this.apitestinfos.splice(index, 1)" size="15" />
                </template>
                <template v-if="edit">
                    <Icon type="md-add-circle" style="color: #2b85e4;"
                        @click="this.api_urls.push(''); this.apitestinfos.push({})" size="15" />
                </template>
                <br>
                <template v-for="apitestinfo in apitestinfos">
                    <div v-if="Object.keys(apitestinfo).length" class="info-card">
                        <div class="header_style">
                            <p style="height: 35px;">
                                &nbsp;&nbsp;
                                <a target="_blank" :href="apitestinfo.url"
                                    style="font-weight: bold;font-size: 20px;margin-left: 5px;line-height: 35px;">
                                    {{ apitestinfo.data.name }}
                                </a>
                                <span
                                    style="float:right; position: relative;margin-right: 10px;line-height: 35px;">运行时间：{{
                                        apitestinfo.data.timings.started }}</span>
                            </p>
                        </div>
                        <div class="center_style">
                            <table id="my_table">
                                <thead>
                                    <tr>
                                        <th></th>
                                        <th>总数</th>
                                        <th>失败数</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <th>用例条目</th>
                                        <th>{{ apitestinfo.data.stats.iterations.total }}</th>
                                        <th>{{ apitestinfo.data.stats.iterations.failed }}</th>
                                    </tr>
                                    <tr>
                                        <th>请求接口</th>
                                        <th>{{ apitestinfo.data.stats.requests.total }}</th>
                                        <th>{{ apitestinfo.data.stats.requests.failed }}</th>
                                    </tr>
                                    <tr>
                                        <th>断言数</th>
                                        <th>{{ apitestinfo.data.stats.assertions.total }}</th>
                                        <th>{{ apitestinfo.data.stats.assertions.failed }}</th>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <br>
                        <div class="center_style">
                            <p>
                                <span style="display: inline-block;width: 5%;"></span>
                                <span class="fontstyle" style="display: inline-block;width: 25%;">
                                    平均响应字节数： {{ apitestinfo.data.timings.firstByteAverage.toFixed(2) }}Byte</span>
                                <span class="fontstyle" style="display: inline-block;width: 25%;">
                                    平均响应时长： {{ apitestinfo.data.timings.responseAverage.toFixed(2) }}ms</span>
                            </p>
                            <p>
                                <span style="display: inline-block;width: 5%;"></span>
                                <span class="fontstyle" style="display: inline-block;width: 25%;">
                                    通过率： {{
                                        (apitestinfo.data.stats.steps.passed / apitestinfo.data.stats.steps.passed *
                                            100).toFixed(2)
                                    }}%</span>
                                <span class="fontstyle" style="display: inline-block;width: 25%;">
                                    失败率： {{
                                        (apitestinfo.data.stats.steps.failed / apitestinfo.data.stats.steps.passed *
                                            100).toFixed(2)
                                    }}%</span>
                            </p>
                            <br>
                        </div>
                    </div>
                </template>
            </template>
            <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 target="_blank" 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 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>
            <Button shape="circle" style="margin-top: 10px;margin-bottom: 10px;" type="primary">bug记录</Button>
            <Table :columns="bugcolumns" :data="bug">
                <template #summary="{ row, index }">
                    <a target="_blank" :href='"http://jira.galaxy-immi.com/browse/" + row.key'>
                        <u>{{ row.summary }}</u>
                    </a>
                </template>
                <template #create="{ row, index }">
                    <p>
                        {{ row.extraFields ? row.extraFields[1].html : '' }}
                    </p>
                </template>
                <template #priority="{ row, index }">
                    <p>
                        {{ priorityMap[row.priorityId] }}
                    </p>
                </template>
                <template #Severity="{ row, index }">
                    <p>
                        {{ row.Severity }}
                    </p>
                </template>
                <template #status="{ row, index }">
                    <p>
                        {{ statusMap[row.statusId] }}
                    </p>
                </template>
                <template #people="{ row, index }">
                    <p>
                        {{ row.ascription }}
                    </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>
            <template v-if="plugs.includes('自动化运行结果')">
                <Button shape="circle" style="margin-top: 10px;margin-bottom: 10px;" type="primary">自动化运行结果</Button>
                <Table :columns="script_result_columns" :data="jenkis_data">
                    <template #name="{ row, index }">
                        <a target="_blank" :href="row.reportPath">
                            <u>{{ row.job }}</u>
                        </a>
                    </template>
                    <template #time="{ row, index }">
                        <p>
                            {{ row.time }}
                        </p>
                    </template>
                    <template #total="{ row, index }">
                        <p>
                            {{ row.total }}
                        </p>
                    </template>
                    <template #success="{ row, index }">
                        <p>
                            {{ row.success }}
                        </p>
                    </template>
                    <template #fail="{ row, index }">
                        <p>
                            {{ row.fail }}
                        </p>
                    </template>
                    <template #abf="{ row, index }">
                        <p>
                            {{ row.success && row.total ? (parseInt(row.success) / parseInt(row.total) * 100).toFixed(2)
                                +
                                '%' : ''
                            }}
                        </p>
                    </template>
                </Table>
            </template>
        </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="bug_s_column" style="height: 300px"></v-chart></Col>
                <!-- <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>
        <div style="background-color: #e8eaec;" v-html="mailbody">
        </div>
        <Spin size="large" fix :show="spinShow"></Spin>
    </Card>
    <Space wrap>
        <Modal title="选择收件人" v-model="modlShow" class-name="vertical-center-modal" @on-cancel="closeShow()">
            <Select filterable v-model="sendto" multiple style="width:260px;margin-bottom: 15px" placeholder="收件人">
                <Option v-for="item in emailList" :value="item.address" :key="item.id">{{ item.name }}</Option>
            </Select>
            <Select filterable v-model="sendcc" multiple style="width:260px" placeholder="抄送人">
                <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>
        <Modal title="运行脚本" v-model="runscriptShow" class-name="vertical-center-modal"
            @on-cancel="runscriptShow = false">
            <CheckboxGroup v-model="run_script">
                <Checkbox v-for="item in all_script" :label="item.name" border style="margin-top: 10px;"></Checkbox>
            </CheckboxGroup>
            <template #footer>
                <Button @click="runscriptShow = false">取消</Button>
                <Button type="primary" @click="runscript">确认</Button>
            </template>
        </Modal>
        <Modal title="保存" v-model="stagingshow" class-name="vertical-center-modal"
            @on-cancel="stagingshow = false; this.remark = null">
            备注：<Input v-model="remark" maxlength="200" show-word-limit type="textarea" :rows="4"
                placeholder="请输入备注消息" />
            <template #footer>
                <Button @click="stagingshow = false; this.remark = null">取消</Button>
                <Button type="primary" @click="stagingreport(0, () => { stagingshow = false; })">确认</Button>
            </template>
        </Modal>
        <Modal v-model="auditshow">
            <p>自动化脚本通过率未全部达到100%，需要提交审核</p>
            <template #footer>
                <Button @click="stagingshow = false; this.remark = null">取消</Button>
                <Button type="primary" @click="toaudit">提交审核</Button>
            </template>
        </Modal>
    </Space>
</template>

<script>
import html2canvas from "html2canvas";
export default {
    props: ['isCollapsed'],
    data() {
        return {
            reportid: null,
            pagestatus: null,
            audit_status: null,
            defaultvalue: "",
            modlShow: false,
            runscriptShow: false,
            stagingshow: false,
            auditshow: false,
            reporttype: null,
            self: null,
            spinShow: false,
            sendto: [],
            sendcc: [],
            defaultcc: [],
            emailList: [],
            jenkis_data: [],
            run_script: [],
            all_script: [],
            plugs: [],
            remark: null,
            api_urls: [''],
            apitestinfos: [{}],
            receive_time: null,
            receive_mails: [],
            mail_id: null,
            options1: {
                shortcuts: [
                    {
                        text: '今日',
                        value() {
                            return new Date();
                        }
                    },
                    {
                        text: '昨日',
                        value() {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24);
                            return date;
                        }
                    }
                ]
            },
            jenkins_columns: [
                {
                    title: '脚本名',
                    key: 'job'
                },
                {
                    title: '最近运行时间',
                    key: 'time'
                }, {

                    title: '状态',
                    slot: 'action',
                    align: 'center'

                }
            ],
            assert_columns: [
                {
                    title: '名称',
                    slot: 'name',
                },
                {
                    title: '结果',
                    slot: 'result',
                },
                {
                    title: '详情',
                    slot: 'defautl',
                },
            ],
            script_result_columns: [
                {
                    title: '脚本名',
                    slot: 'name',
                },
                {
                    title: '运行时间',
                    slot: 'time',
                },
                {
                    title: '用例总数',
                    slot: 'total',
                }, {

                    title: '成功数',
                    slot: 'success',
                    align: 'center'
                },
                {

                    title: '失败数',
                    slot: 'fail',
                    align: 'center'
                },
                {
                    title: '通过率',
                    slot: 'abf',
                    align: 'center'
                }
            ],

            bug_p_column: {
                title: {
                    text: 'bug优先级占比',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left'
                },
                series: [
                    {
                        name: '优先级',
                        type: 'pie',
                        radius: '50%',
                        data: [
                        ],
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            }, bug_s_column: {
                title: {
                    text: 'bug严重程度占比',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left'
                },
                series: [
                    {
                        name: '严重程度',
                        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: [],
            views: [],
            iterations: [],
            ReC: {
                project: null,
                view: 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'
                }
            ],
            bugcolumns: [
                {
                    title: 'BUG',
                    slot: 'summary'
                },
                {
                    title: '提出人',
                    slot: 'create'
                },
                {
                    title: '优先级',
                    slot: 'priority'
                },
                {
                    title: '严重程度',
                    slot: 'Severity'
                },
                {
                    title: '状态',
                    slot: 'status'
                },
                {
                    title: '修复人',
                    slot: 'people'
                }
            ],
            info: {
                project: null,
                sprint: null
            },
            statusMap: {},
            priorityMap: {},
            typeMap: {},
            caseCount: 0,
            fugailu: 0,
            timeoutFun: [],
            mailbody: null,
            quit: false,
        }
    },
    methods: {
        dateToString(date) {
            var year = date.getFullYear();
            var month = (date.getMonth() + 1).toString();
            var day = (date.getDate()).toString();
            if (month.length == 1) {
                month = "0" + month;
            }
            if (day.length == 1) {
                day = "0" + day;
            }
            var dateTime = year + "-" + month + "-" + day;
            return dateTime;
        },
        getreportbyid(id) {
            this.$request("get", "/tool/testport/getreport/" + id, null, this, (data) => {
                this.remark = data.data.save_remark
                this.reporttype = data.data.type
                this.audit_status = data.data.audit_status
                this.self = data.data.self
                const result = JSON.parse(data.data.report_data)
                this.info = result.info
                this.testResult = result.testResult
                this.mycase = result.mycase
                this.story = result.story
                this.case = result.case
                this.bug = result.bug
                this.fengxxian = result.fengxxian
                this.apitestinfos = result.apitestinfos
                this.api_urls = result.api_urls
                this.bug = result.bug
                this.plugs = result.plugs
                this.jenkis_data = result.jenkis_data
                this.myname = result.myname
                this.people = result.people,
                    this.statusMap = result.statusMap,
                    this.priorityMap = result.priorityMap,
                    this.typeMap = result.typeMap,
                    this.caseCount = result.caseCount,
                    this.fugailu = result.fugailu
            })
        },
        stagingreport(requets_type, suback = () => { })
        /**
         * requets_type 请求环境 0-保存按钮驱动 1-发送成功后的请求 2-需要审核时的请求
         * 
         */ {
            const report_data = JSON.stringify(
                {
                    info: this.info,
                    testResult: this.testResult,
                    mycase: this.mycase,
                    story: this.story,
                    bug: this.bug,
                    fengxxian: this.fengxxian,
                    apitestinfos: this.apitestinfos,
                    api_urls: this.api_urls,
                    bug: this.bug,
                    plugs: this.plugs,
                    jenkis_data: this.jenkis_data,
                    myname: this.myname,
                    people: this.people,
                    case: this.case,
                    statusMap: this.statusMap,
                    priorityMap: this.priorityMap,
                    typeMap: this.typeMap,
                    caseCount: this.caseCount,
                    fugailu: this.fugailu
                }
            )
            const type = requets_type == 0 || requets_type == 1 ? 0 : 1
            const report_status = requets_type == 0 || requets_type == 2 ? 0 : 1
            var res = { project: this.info.project, sprint: this.info.sprint, save_remark: this.remark, type, report_status, report_data }
            const a = () => {
                if (requets_type == 1) {
                    this.$router.push('reportlsit')
                }
                if (requets_type == 2) {
                    this.$router.push('aduitreportlist')
                }
            }
            if (this.reportid && requets_type != 2) {
                res.id = this.reportid
                this.$request('post', '/tool/testport/updatereport', res, this, () => { suback(), a() })
            } else {
                this.$request('post', '/tool/testport/staging', res, this, () => { suback(), a() })
            }
        },
        changeStoryList() {
            this.story = this.$refs.stroy.getSelection()
        },
        breforesend() {
            if (!this.report) return this.$Message.error("请先完善报告信息")
            if (this.fugailu < 100) return this.$Message.error("用例覆盖率不足100%（每个需求必须关联测试用例）")
            if (!this.apitestinfos && this.plugs.includes("左移-接口测试")) return this.$Message.error("请先关闭'左移-接口测试'或完善'左移-接口测试'信息")
            if (this.plugs.includes("自动化运行结果") && this.audit_status != 1 && this) {
                for (var i of this.jenkis_data) {
                    if (!i.success || !i.total || ((parseInt(i.success) / parseInt(i.total)) != 1)) {
                        return this.auditshow = true
                    }
                }
            }
            this.edit = false;
            this.getallEmail();
            this.getdefaultCC();
            this.modlShow = true;
        },
        toaudit() {
            this.stagingreport(2);
            this.auditshow = false;
        },
        renderapihtml(url, index) {
            if (!this.api_urls || !url) return
            console.info(url)
            this.$request("post", '/tool/testport/getapitestinfo', { url: url.indexOf('?') == -1 ? url : url.slice(0, url.indexOf('?')) }, this, (data) => {
                this.apitestinfos[index] = data.data
            })
        },
        show() {
            var info = ''
            if (this.testResult.includes("测试不通过")) {
                const a = this.testResult.split("测试不通过")
                for (var i = 0; i < a.length; i++) {
                    info = i < a.length - 1 ? info + '<span>' + a[i] + '</span><span style="font-weight: bold;color: #ed4014;">测试不通过</span>' : info + '<span>' + a[i] + '</span>'
                }
            } else if (this.testResult.includes("测试通过")) {
                const a = this.testResult.split("测试通过")
                console.info(a)
                for (var i = 0; i < a.length; i++) {
                    info = i < a.length - 1 ? info + '<span>' + a[i] + '</span><span style="font-weight: bold;color: #19be6b;">测试通过</span>' : info + '<span>' + a[i] + '</span>'
                }
            } else {
                info = '<span>' + this.testResult + '</span>'
            }
            document.getElementById("jielun").innerHTML = info
            this.spinShow = false
        },
        searchCaseBykey(key) {
            const index = this.mycase.findIndex(ele => { return ele.key == key })
            return index == -1 ? null : this.mycase[index]
        },
        getJenkinsInfo() {
            this.$request("get", '/tool/testport/runresult', null, this, (data) => {
                if (!this.quit) {
                    this.jenkis_data = data.data;
                    const funid = setTimeout(() => {
                        this.getJenkinsInfo();
                        const index = this.timeoutFun.findIndex(ele => { return ele == funid });
                        this.timeoutFun.splice(index, 1);
                    }, 5000);
                    this.timeoutFun.push(funid)
                }
            })
        },
        breforerunjenkins() {
            this.$request("get", "/tool/testport/allscript", null, this, (data) => {
                this.all_script = data.data;
                this.run_script = this.all_script.map((each) => { return each.name })
                this.runscriptShow = true;
            })
        },
        runscript() {
            this.$request("post", "/tool/testport/runjobs", this.run_script, this, () => {
                this.runscriptShow = false;
            })
        },
        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.view = null; this.ReC.iteration = null })
        },
        getview(project) {
            this.$request('get', 'tool/testport/view/' + project, null, this, (data) => { this.views = data.data; this.ReC.iteration = null })
        },
        getiterations(view) {
            if (view == null) return
            this.$request('get', 'tool/testport/iteration/' + view, null, this, (data) => { this.iterations = data.data })
        }, getReportInfo() {
            this.spinShow = true
            if (!this.ReC.iteration) return
            if (this.edit) this.edit = !this.edit
            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
            }
        },
        getdefaultCC() {
            this.$request('get', '/tool/testport/defaultCClist', null, this, (data) => { this.defaultcc = data.data })
        },
        render() {
            this.report = true
            setTimeout(() => {
                this.show()
            }, 50);
        },

        backdoor() {
            console.info(this.bug_s_column.series[0].data)
            const a = this.bug_s_column.series[0].data.filter(item => { if (item.name == '严重') return item })
            console.info(a)
            if (a.length > 0) {
                const sub = '测试报告存在严重bug预警'
                const info = '报告对象：' + this.info.project + "-" + this.info.sprint + "测试报告\n严重bug数：" + a[0].value
                const target = ['nanci.cxn@galaxyoversea.com', 'eifel.dpf@galaxyoversea.com', 'betty.zww@galaxyoversea.com']
                this.$request("post", "/tool/testport/sendport", { to: target, subject: sub, cc: [], contents: info })
            }
        },
        async send() {
            if (!this.report) return
            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) continue
                    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 if (j.selectorText.includes("ivu-btn") || j.selectorText.includes("ivu-typography") || j.selectorText.includes("ivu-table") || j.selectorText.includes("body") || j.selectorText.includes("info-card") || j.selectorText.includes("my_table")
                        || j.selectorText.includes("header_style") || j.selectorText.includes("center_style") || j.selectorText.includes("background_sytle") || j.selectorText.includes("near_left") || j.selectorText.includes("near_right") || j.selectorText.includes("fontstyle")) { stylestart = stylestart + j.cssText }
                }
            }
            const c = (stylestart + styleend + html).replace(/style="width(.*?)"/gm, 'style="width:100%"')
            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 sendinfo = this.receive_mails.filter(each => { return each.id == this.mail_id })[0]
                const m = `<img src='${canvas.toDataURL("image/png")}'/>`
                const q = sendinfo?`<p></p><p></p><p>${sendinfo.from}于${sendinfo.receive_time}写道：</P>`:''
                const result = c + m + q + this.mailbody
                const sub = this.info.project + "-" + this.info.sprint + "测试报告"
                this.closeShow()
                this.backdoor()
                this.$request("post", "/tool/testport/sendport", { to: this.sendto, cc: this.sendcc, subject: sub, contents: result }, this, () => { this.sendto = []; this.stagingreport(1, () => { this.$router.push('reportlsit') }) })
            });
        },

        getallEmail() {
            this.$request("get", "/tool/testport/emailuserlist", null, this, (data) => { this.emailList = data.data })
        },
        closeShow() {
            this.modlShow = false
        }, colorstyle(number) {
            return number ? "color: #515a6e;" : "color: #ed4014;"
        }
    },
    watch: {
        edit(value) {
            const a = {
                title: ' ',
                slot: 'action'
            }
            const b = {
                type: 'selection',
                width: 60,
                align: 'center'
            }
            if (value) {
                this.storycolumns.push(a)
                this.bugcolumns.push(a)
                this.casecolumns.push(a)
                this.storycolumns.unshift(b)
            } 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' })
                const index4 = this.storycolumns.findIndex(ele => { return ele.type == 'selection' })
                index1 == -1 || this.storycolumns.splice(index1, 1)
                index2 == -1 || this.bugcolumns.splice(index2, 1)
                index3 == -1 || this.casecolumns.splice(index3, 1)
                index4 == -1 || this.storycolumns.splice(index4, 1)
                setTimeout(() => {
                    this.show()
                }, 50);
            }
        },
        defaultcc: {
            handler(value) {
                this.sendcc = value.map(ele => { return ele.address })
            }, deep: true
        },
        bug: {
            handler(value) {
                this.bug_p_column.series[0].data = []
                this.bug_s_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 sinfo = {}
                    var dateinfo = {}
                    var bugUser = {}
                    value.forEach(ele => {
                        console.info(ele)
                        ele.priorityId in pinfo ? pinfo[ele.priorityId]++ : pinfo[ele.priorityId] = 1
                        ele.Severity in sinfo ? sinfo[ele.Severity]++ : sinfo[ele.Severity] = 1
                        // let date = ele.extraFields[1].html.split(' ')[0] || ''
                        let date = null
                        if (ele.extraFields) {
                            const index = ele.extraFields?.findIndex(ele => { return ele.id == "created" }) || -1
                            date = index != -1 ? ele.extraFields[index].html.split(' ')[0] : 0
                        } else {
                            date = null
                        }
                        date in dateinfo ? dateinfo[date]++ : dateinfo[date] = 1
                        ele.ascription in bugUser ? bugUser[ele.ascription]++ : bugUser[ele.ascription] = 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 sinfo) {
                        this.bug_s_column.series[0].data.push({ value: sinfo[i], name: 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 && ele.case.length > 0) {
                            b += 1
                        };
                        a += 1
                    })
                    value.forEach(ele => {
                        if (ele.extraFields) {
                            const index = ele.extraFields.findIndex(item => { return item.id == "created" })
                            ele.start = index != -1 ? ele.extraFields[index].html.split(" ")[0] : ''
                        }
                        else ele.start = ''
                        ele.end = new Date().toLocaleDateString()
                        this.case.forEach(each => {
                            if (ele.case && 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
        },
        receive_time: {
            handler(value) {
                if (value) {
                    this.$request('get', '/tool/testport/getMail', { date: this.dateToString(value) }, this, (data) => {
                        this.receive_mails = data.data
                    })
                }
            }, deep: true
        },
        mail_id: {
            handler(value) {
                if (value) {
                    this.$request('get', '/tool/testport/getMailDeatil/' + value, null, this, (data) => {
                        this.mailbody = data.data
                    })
                }
            }
        }
    },
    created() {
        this.pagestatus = parseInt(localStorage.getItem("pagestatus"))
        this.reportid = parseInt(localStorage.getItem("reportid"))
        this.remark = localStorage.getItem("save_remark")
        if (this.reportid) {
            this.getreportbyid(this.reportid)
            this.render()
        } else {
            this.getprojects();
            this.getJenkinsInfo();
            this.myname = JSON.parse(localStorage.getItem("userinfo")).name
        }
    },
    beforeUnmount() {
        this.quit = true
        this.timeoutFun.forEach(ele => {
            clearTimeout(ele)
        })
    },
    mounted() {
    }
};
</script>

<style type="text/css">
.chart {
    height: 100vh;
}

.info-card {
    margin: 10px 5px 10px 5px;
    background-color: rgb(255, 255, 255);
    border-radius: 8px;
    /* text-align: center; */
    box-shadow: 0px 0px 8px 0px rgba(180, 180, 180, 0.58);
}

#my_table {
    text-align: left;
    width: 90%;
    margin: 0px 10px 10px 10px;
    margin-right: auto;
    margin-left: auto;
}

#my-table td:nth-child(1) {
    width: 80%;
}

#my-table td:nth-child(2) {
    width: 10%;
}

.header_style {
    border-bottom: 1px solid #dcdee2;
}

.center_style {
    width: 90%;
    margin: auto
}

.background_sytle {
    background-color: #f8f8f9;
    padding-top: 0.5px;
    padding-bottom: 0.5px;
    border-radius: 8px;
    margin-top: 2px;
    margin-bottom: 2px;
}

.near_left {
    width: 25%;
    display: inline-block;
    height: 100%;
}

.near_right {
    width: 75%;
    display: inline-block
}

.fontstyle {
    text-align: left;
}






@keyframes changDeg {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}


.demo-spin-icon-load {
    color: #2b85e4;
    animation: changDeg 2s linear 0.2s infinite;
}
</style>