<template>
    <div class="testdiv">
        <div class="divborder newSearchDiv" style="margin:0px;">
            <div class="filter">
                <label>{{$t('1132')}}：</label>
                <Cascader
                    :data="datalevel"
                    :value="leveldata"
                    trigger="click"
                    change-on-select
                     class="searchSelect"
                    @on-change="getlevel"
                ></Cascader>
            </div>
            <div class="filter">
                <label>{{$t(900910)}}</label>
                <Select
                  v-model="datetype"
                  label-in-value
                  clearable
                   class="searchSelect"
                  @on-change="timechange"
                >
                  <Option :value="1" id="今天">{{$t("900911")}}</Option>
                  <Option :value="2" id="昨天">{{$t("900390")}}</Option>
                </Select>

            </div>
            <div class="filter">
                <label>{{$t('900908')}}：</label>
                <DatePicker
                    type="datetimerange"
                    :value="dateTime"
                    placeholder=""
                    class="searchInput MaxWidth "
                    @on-change="selectdate"
                ></DatePicker>
            </div>
            <div class="filter">
                <label> {{$t('900862')}}</label>
                <Select v-model="oddType" label-in-value clearable filterable  class="searchSelect">
                    <Option
                        v-for="(item,key) in expectionList"
                        :value="item.id"
                        :key="key"
                    >{{ item.name }}</Option>
                </Select>
            </div>
            <div class="searchBtn">
                <Button type="primary" class="twoWord" icon="ios-search" @click="search(0)">{{$t('1001')}}</Button>
                <Button type="warning" class="twoWord intervalRight" icon="ios-create-outline" @click="edit()">{{$t('1003')}}</Button>
                <Button type="primary" class="fourWord" icon="ios-cloud-download" @click="search(1)">{{$t('1007')}}</Button>
            </div>
        </div>
        <div class="divborder newTableDiv">
            <Table
                highlight-row
                :data="tableData1"
                :columns="tableColumns1"
                @on-selection-change="getSelection"
                :loading="loading"
                class="tableClass"
            ></Table>
            <div class="pageDiv">
                <div class="pageDirection">
                    <Page
                        :total="total"
                        :current="page"
                        @on-change="changePage"
                        show-elevator
                        show-sizer
                        show-total
                        @on-page-size-change="handlePageSize"
                        :page-size-opts="[10,20,30,40,100]"
                    ></Page>
                </div>
            </div>
        </div>
        <Modal class="newModalClass" :title="$t('1003')" v-model="editmodal">
            <div class="filter">
                <label style="width:150px">{{$t(9000463)}}：</label>
                <Select v-model="editType" label-in-value clearable filterable class="searchSelect">
                    <Option
                        v-for="(item,key) in expectionList"
                        :value="item.id"
                        :key="key"
                    >{{ item.name }}</Option>
                </Select>
            </div>
            <div slot="footer">
                <Button type="text" size="large" v-text="$t(1033)" @click="cancel">{{$t(1033)}}</Button>
                <Button type="primary" size="large" @click="editPost()">{{$t('1011')}}</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import moment from 'moment';
import axios from '@/libs/api.request';
export default {
    components: {},
    data () {
        return {
            leveldata: [], // 产线层级集合
            treedata1: [],
            datalevel: [],
            levelid: 0, // 产线层级id
            fastDate: this.$t(900911), // 快捷日期
            tableData1: [], // 列表数据
            dateTime: [], // 时间范围
            starttime: '', // 开始时间
            endtime: '', // 结束时间
            expectionList: [], // 异常类型列表
            datetype: '',
            editType: 0, // 修改异常类型
            oddType: 0, // 查询异常类型
            idList: [], // 多个修改
            obj: {},
            selection: [],
            editmodal: false,
            date1: '',
            total: 0,
            page: 1,
            morecondition: false,
            pagesize: 10,
            loading: true,
            tableColumns1: [
                {
                    type: 'selection',
                    width: 50,
                    align: 'center'
                },
                {
                    type: 'index2',
                    title: this.$t('1008'),
                    key: 'xuhao',
                    render: (h, params) => {
                        return h(
                            'span',
                            params.index + (this.page - 1) * this.pagesize + 1);
                    },
                    width: 80
                },
                {
                    title: this.$t(5000009), // 通道
                    key: 'sectionName',
                    width: 100
                },
                {
                    title: this.$t(700184), // 损失类型
                    key: 'type_name'
                },
                {
                    title: this.$t(960412), // 二级异常
                    key: 'expection2',
                    width: 120
                },
                {
                    title: this.$t(960413), // 三级异常
                    key: 'expection3',
                    width: 120
                },
                {
                    title: this.$t(960414), // 责任岗位
                    key: 'usergroup_name',
                    width: 120
                },
                {
                    title: this.$t(1049), // 开始时间
                    key: 'startTime'
                },
                {
                    title: this.$t(1050), // 结束时间
                    key: 'endTime'
                },
                {
                    title: this.$t(700185), // 损失时长（分钟）
                    key: 'subtraction',
                    width: 120
                },
                {
                    title: this.$t(900337), // 损失时长（分钟）
                    key: 'workOrderId',
                    render: (h, params) => {
                        if (params.row.workOrderId != '') {
                            return h('div', [
                                h(
                                    'Button',
                                    {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            marginRight: '5px'
                                        },
                                        on: {
                                            click: () => {
                                                this.JumpPage(
                                                    params.row.workOrderId
                                                );
                                            }
                                        }
                                    },
                                    params.row.workOrderId
                                )
                            ]);
                        }
                    }
                },
                {
                    title: this.$t(100016), // 修改人员
                    key: 'editor_name'
                },
                {
                    title: this.$t(700138), // 修改时间
                    key: 'rel_edit_time'
                }
            ]
        };
    },
    created () {
        this.initlevel();
        this.inittime(); // 初始化
        this.search(0);
        this.getFirstLevelExpection();
        this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1)
    },
    methods: {
    // 跳转页面
        JumpPage: function (e) {
            if (e === '' || e === 0) {
                return false;
            }
            // this.$router.push({ path: '/realtime/passageway', query: { passid: e } })
            let routeUrl = this.$router.resolve({
                path: '/andon/abnormalrecords',
                query: { work_order: e }
            });
            window.open(routeUrl.href, '_blank');
        },
        // 产线层级
        initlevel () {
            axios
                .request({
                    url: 'config/ProjectLevelSection/GetSectionTree',
                    method: 'get'
                })
                .then(res => {
                    const arr = [];
                    this.datalevel = res.data.data;
                    arr.push(res.data.data[0].value);
                    this.leveldata = arr;
                });
        },
        // 产线层级选择
        getlevel: function (data) {
            // if(data.length<=2){
            //   this.$Message.error()
            // }
            this.levelid = data[data.length - 1];
            // this.getLevels();
        },
        getFirstLevelExpection () {
            axios
                .request({
                    url: 'tpm/AndonSummary/GetFirstLevelExpection',
                    method: 'get'
                })
                .then(res => {
                    const arr = [];
                    if (res.data.ret == 1) {
                        this.expectionList = res.data.data;
                    }
                });
        },
        timechange () {
            let datetime = this.$time.changetime(this.datetype)
            let dt = datetime.split(' - ')
            this.dateTime = [dt[0], dt[1]]
        },
        inittime () {
            let dt = new Date();
            var date = this.$time.getDate(0, 1);
            var hour = date + ' 08:10:00';
            var now =
                date + ' ' + dt.getHours() + ':' + dt.getMinutes() + ':00';
            var hour1 = date + ' 00:10:00';
            if (now > hour) {
                // 如果现在时间大于8小时，时间段就是8点到现在时间减去10分钟
                this.dateTime = [
                    date + ' 08:00:00',
                    this.$time.timestampToTimeSpan(
                        (Date.parse(now) - 10 * 60 * 1000) / 1000
                    )
                ];
            } else {
                if (now < hour1) {
                    this.dateTime = [
                        date + ' 00:00:00',
                        this.$time.timestampToTimeSpan(now / 1000)
                    ];
                } else {
                    this.dateTime = [
                        date + ' 00:00:00',
                        this.$time.timestampToTimeSpan(
                            (Date.parse(now) - 10 * 60 * 1000) / 1000
                        )
                    ];
                }
            }
        },
        getSelection (value) {
            // 监听选择变化
            this.idList = [];
            this.selection = value;
            for (let i = 0; i < this.selection.length; i++) {
                this.idList.push(this.selection[i].id);
            }
        },
        edit () {
            if (this.selection.length > 0) {
                this.editType = 0;
                this.editmodal = true;
            } else {
                this.$Message.error(this.$t(9000396));
            }
        },
        editPost () {
            let params = {
                id: this.idList.join(','),
                type: this.editType
            };
            // return false;
            axios
                .request({
                    url: '/tpm/AndonSummary/SetOeeData',
                    params,
                    method: 'get'
                })
                .then(res => {
                    const arr = [];
                    if (res.data.ret == 1) {
                        this.search(0);
                        this.selection = [];
                        // this.expectionList = res.data.data;
                        this.editmodal = false;
                    }
                });
        },
        selectdate (e) {
            this.dateTime = [e[0], e[1]];
            let dtStart = e[0];
            let dtEnd = e[1];
            let last_str = dtEnd.split(' ')[1];
            if (last_str == '00:00:00') {
                dtEnd = moment(dtEnd).format('YYYY-MM-DD') + ' 23:59:59';
                this.dateTime = [dtStart, dtEnd];
            }
        },
        search (toexcel) {
            if (this.dateTime === undefined || this.dateTime === '') {
                this.$Message.error(this.$t('800154'));
                return false;
            }
            let date1 = new Date(this.dateTime[0]);
            let date2 = new Date(this.dateTime[1]);

            this.starttime = date1.getTime() / 1000;
            this.endtime = date2.getTime() / 1000;

            let data = {
                section: this.levelid,
                type: this.oddType,
                start: this.starttime,
                end: this.endtime,
                toexcel: toexcel,
                page: this.page,
                pagesize: this.pagesize
            };
            axios
                .request({
                    url: 'tpm/AndonSummary/GetOeeData',
                    data,
                    method: 'post'
                })
                .then(res => {
                    if (toexcel === 0) {
                        if (res.data.ret == 1) {
                            this.loading = false;
                            this.total = res.data.total;
                            this.mockTableData1(res.data.data);
                        }
                    } else {
                        if (res.data.ret === 1) {
                            let long = this.endtime - this.starttime;
                            if (long > 24 * 60 * 60) {
                                this.$Message.error(this.$t(90000093));
                            } else {
                                document.location.href =
                                    axios.publicPath + '' + res.data.data;
                            }
                        } else {
                            this.$Message.error(this.$t('1000039'));
                        }
                    }
                });
        },
        mockTableData1 (tablelist) {
            let data = [];
            if (tablelist && tablelist.length > 0) {
                tablelist.forEach(item => {
                    if (item) {
                        data.push({
                            title: item.title,
                            rel_edit_time: item.rel_edit_time,
                            str_editTime: item.str_editTime,
                            editor: 0,
                            editor_name: item.editor_name,
                            endTime: item.endTime,
                            hour: 0,
                            id: item.id,
                            rel_edit_time: item.rel_edit_time
                                ? moment(item.rel_edit_time).format(
                                    'YYYY-MM-DD HH:mm:ss'
                                )
                                : '',
                            sectionID: item.sectionID,
                            sectionName: item.sectionName,
                            startTime: item.startTime,
                            status: 0,
                            subtraction: item.subtraction,
                            type: item.type,
                            type_name: item.type_name,
                            workOrderId: item.workOrderId,
                            yield: item.yield,
                            usergroup_name: item.usergroup_name,
                            expection2: item.expection2,
                            expection3: item.expection3
                        });
                    }
                });
            }
            this.tableData1 = data;
        },
        handleRowChange (currentRow, oldCurrentRow) {
            this.currentObj = currentRow;
        },
        handlePageSize (value) {
            this.pagesize = value;
            this.search(0);
        },
        changePage (value) {
            this.page = value;
            this.search(0);
        },
        cancel () {
            this.editmodal = false;
        }
    }
};
</script>
<style lang="less" scoped>

</style>
