<template>
  <div class="andonSlice">
    <div class="divborder">
      <div class="filter">
        <label>{{$t(1132)}}:</label>
        <Cascader :data="datalevel" :value="leveldata" trigger="hover" style="display:inline-block;width:200px;"
          @on-change="changelevel"></Cascader>
      </div>
      <div class="buttonall">
        <Button type="primary" @click="search(1,10)">{{$t('1001')}}</Button>
        <Button type="primary" @click="toExcel()" v-text="$t(1007)">导出Excel</Button>
      </div>
    </div>

    <div class="divborder">
      <Table style="margin-top:10px" width='100%' :data="tableData1" :columns="tableColumns1"></Table>
    </div>

    <Modal :title="$t(950420)" v-model="optModal" footer-hide :loading="loading" :styles="{top: '40px',width:'900px',overflow: 'visible'}">
      <div class="modal_body" style="width:100%!important;padding:0 15px;min-height: 320px;overflow: visible;">
        <Form ref="optObj" :model="optObj" label-position="left" :label-width="80">
          <Table style="margin-top:10px;overflow:visible;" width='100%' :data="tableData2" :columns="tableColumns2"></Table>
          <div style="margin: 10px;overflow: hidden">
            <div style="float: right;">
              <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>
          <Row type="flex" justify="space-between" class="code-row-bg">
            <Col span="11">
            <span>{{$t(7000028)}}:</span><span class="fs20 pl10 pr10">{{optObj.andonCount}}</span><span>次</span><span class="pl20">{{$t(7000029)}}：</span><span
              class="fs20 pl10 pr10">{{optObj.andonTime}}</span><span>分钟</span>
            </Col>
            <Col span="13">
            <Button v-show="!optObj.hasVal" type="primary" @click="saveAndon()">{{$t(900306)}}</Button>
            </Col>
          </Row>
        </Form>
      </div>
    </Modal>

  </div>
</template>
<script>
import axios from '@/libs/api.request'
export default {
    name: 'tpm-andon-slice',
    components: {

    },
    // data ************************************************************************************
    data () {
        return {
            leveldata: [], // 产线层级插件所需数据
            datalevel: [], // 产线层级选中数据
            levelid: 0, // 产线层级选中的section_id

            filterObj: {
                typeMode: 0,
                timeRange: []
            },

            optObj: {
                machineid: 0,
                hasVal: false, // 是否有值，影响到tab2,3的按钮是否显示
                todayObj: [],
                andonCount: 0,
                andonTime: 0
            },

            total: 0, // 列表total
            page: 1, // 列表当前页数
            pagesize: 10, // 列表pagesize
            optModal: false,
            loading: false,
            expectionLevel: [], // 异常级别全部数据
            expectionLeveldata: [], // 产线层级value [1,2,4]
            tableData2: [], // 今日记录
            tableColumns2: [{
                title: this.$t(200054),
                key: 'status', // 0正常 1安灯 2停机
                width: 60,
                render: (h, params) => {
                    return h('span', params.row.status === 2 ? this.$t(200173) : (params.row.status === 1 ? this.$t(7000046) : this.$t(100200)))
                }
            },
            {
                title: this.$t(950312),
                key: 'expection3',
                width: 200,
                render: (h, params) => {
                    if (params.row.expection3 != '') { // params.row.expection3 != ''
                        return h('span', params.row.expection3)
                    } else {
                        return h('Cascader', {
                            props: {
                                value: [],
                                data: this.expectionLevel,
                                trigger: 'click',
                                changeOnSelect: true
                            },
                            style: {
                                width: '180px',
                                overflow: 'auto'
                            },
                            on: {
                                'on-change': (s) => {
                                    if (this.optObj.todayObj.length > 0) {
                                        this.optObj.todayObj.forEach((item, i) => {
                                            if (item.id === params.row.id) {
                                                this.optObj.todayObj[i].expection1 = s[0] === undefined ? 0 : s[0]
                                                this.optObj.todayObj[i].expection2 = s[1] === undefined ? 0 : s[1]
                                                this.optObj.todayObj[i].expection3 = s[2] === undefined ? 0 : s[2]
                                            }
                                        })
                                    }
                                    console.log(this.optObj.todayObj)
                                }
                            }
                        })
                    } // end else
                } // end render
            },
            {
                title: this.$t(960409),
                key: 'create_time',
                width: 155
            },
            {
                title: this.$t(7000037),
                key: 'complete_time',
                width: 155
            },
            {
                title: this.$t(7000038),
                key: 'andon_cost_time'
                // width: 120
            }
                // {
                //   title: '触发人',
                //   key: 'creator_name',
                //   width: 72
                // },
                // {
                //   title: this.$t(200049),
                //   key: 'handler_name'
                // }
            ],

            tableData1: [], // 列表数据容器
            tableColumns1: [{
                title: this.$t(1046),
                key: 'starttime_show',
                width: 80
            },
            {
                title: this.$t(200054),
                key: 'status',
                width: 90
            },
            {
                title: this.$t(100307),
                key: 'product',
                width: 160
            },
            {
                title: this.$t(900780),
                key: 'target',
                width: 70
            },
            {
                title: this.$t(900107),
                key: 'actually',
                width: 70
            },
            {
                title: this.$t(901010),
                key: 'difference',
                width: 70
            },
            {
                title: this.$t(7000028),
                key: 'andon_count',
                width: 100
            },
            {
                title: this.$t(7000029),
                key: 'andon_time',
                width: 140
            },
            {
                title: this.$t(7000047),
                key: 'andon_info',
                render: (h, params) => {
                    if (params.row.andon_info.length > 0) {
                        // let test_arr = ['a', 'b']
                        // let str = test_arr.join('\n')
                        let str = params.row.andon_info.join('\n')
                        return h('div', {
                            style: {
                                // position:'relative',
                                // width:'100%',
                                justifyContent: 'space-between',
                                flexDirection: 'column',
                                display: 'flex'
                            }
                        }, [
                            h('div', {
                                style: {
                                    width: '60%',
                                    whiteSpace: 'pre-wrap'
                                }
                            }, str),
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginBottom: '5px',
                                    width: '20%',
                                    justifyContent: 'flex-end',
                                    display: 'flex',
                                    float: 'right',
                                    marginLeft: '75%'
                                },
                                on: {
                                    'click': (e) => {
                                        // 获取当前时间段的记录
                                        this.getAndonRecords(params.row.starttime, params.row.endtime, this.optObj.machineid)
                                        this.optModal = true
                                        console.log(params)
                                    }
                                }
                            }, this.$t(7000048))
                        ])
                    } else {

                    }
                }
            }

            ] // end tableColumn1

            // headers: {
            //   token: localStorage.getItem('token'),
            //   timestamp: localStorage.getItem('timestamp'),
            //   nonce: localStorage.getItem('nonce'),
            //   sign: localStorage.getItem('sign')
            // }

        } // end return data
    },
    // created ************************************************************************************
    created () {
        this.defaultPageData()
        this.search(1, 10) // 初始化列表
    // this.initAddModal()
    },
    // methods ************************************************************************************
    methods: {
        defaultPageData () {
            this.initlevel() // 初始化产线层级
            this.initexpectionType()
        },
        initexpectionType () {
            axios
                .request({
                    url: '/tpm/AndonBaseSetting/GetExpectionTypeTree',
                    method: 'get'
                })
                .then(res => {
                    this.expectionLevel = res.data.data
                })
        },
        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
            })
        },
        changelevel (data) { // 切换产线层级，触发事件
            // 请求数据
            let params = {
                sectionid: this.levelid,
                type: 1
            }
            this.levelid = data[data.length - 1]
            axios.request({
                url: '/tools/ToolConfigV2/getProgramListByCutterLocationConfig',
                params,
                method: 'get'
            }).then(res => {
                this.program_list = res.data.data
            })
        },
        changePage (value) { // 换页事件
            this.page = value
            this.tableData2 = this.getAndonRecords(startTime, endTime, machineid)
        },
        handlePageSize (value) { // 切换分页页数，触发事件
            this.pagesize = value
            this.tableData2 = this.getAndonRecords(startTime, endTime, machineid)
        },
        search (page, pagesize) { // 点击查询，触发事件
            this.optObj.machineid = 403
            this.optObj.startTime = 1581264000
            this.optObj.endTime = 1581868799
            var data = {
                machine: 403,
                start: 1581264000,
                end: 1581868799
            }
            axios.request({
                url: '/tpm/Andon/GetAndonSlice',
                data,
                method: 'post'
            }).then(res => {
                if (res.data.ret === 1) {
                    this.total = res.data.total
                    this.mockTableData1(res.data.data)
                }
            })
        },
        mockTableData1 (tablelist) { // 转换数据，并赋值给列表数据容器tableData1
            let data = []
            tablelist.forEach(item => {
                if (item) {
                    data.push({
                        id: item.id,
                        starttime: item.starttime,
                        starttime_show: this.getTime(item.starttime * 1000),
                        endtime: item.endtime,
                        status: item.status,
                        product: item.product === null ? '' : item.product,
                        target: item.target,
                        actually: item.actually,
                        difference: item.difference,
                        andon_count: item.andon_count,
                        andon_time: item.andon_time === null ? '' : item.andon_time,
                        andon_info: item.andon_info.length > 0 ? item.andon_info : []
                    })
                }
            })
            this.tableData1 = data
        },
        getAndonRecords (startTime, endTime, machineid) {
            let data = {
                page: this.page,
                pagesize: this.pagesize,
                machine: machineid,
                starttime: startTime,
                endtime: endTime
            }
            axios.request({
                url: '/tpm/andon/GetAndonInfo',
                data,
                method: 'post'
            }).then(res => {
                res.data.data = [{
                    'id': 1,
                    'status': 5,
                    'expection_type': 4,
                    'expection1': '', // "测试1",
                    'expection2': '', // "测试211",
                    'expection3': '', // "测试985",
                    'create_time': 1581585276,
                    'creator': 1469,
                    'creator_name': '利达',
                    'handler': 1469,
                    'handler_name': '利达',
                    'handle_time': 1581676474,
                    'complete_time': 1581676530,
                    'machine': 403,
                    'station': 930,
                    'station_name': '5#-车间1-长沙三一',
                    'process_code': 'DE79A41D7B2E44F19A79EBD1E793DBF3',
                    'projectid': 125,
                    'is_shutdown': 0,
                    'approve_time': 1581676783,
                    'andon_cost_time': '1天1小时20分钟54秒',
                    'handle_cost_time': '56秒'
                }]
                if (res.data.ret === 1 && res.data.data.length > 0) {
                    this.optObj.id = res.data.data[0].id
                    this.expectionLeveldata = []

                    this.total = res.data.total
                    this.mockTableData2(res.data.data)
                } else {
                    this.optObj.id = 0
                    this.expectionLeveldata = []
                    this.optObj.hasVal = true // 今日安灯记录没有数据时，直接隐藏保存按钮
                    this.total = 0
                    this.tableData2 = []
                }

                let data = {
                    machine: machineid,
                    starttime: startTime,
                    endtime: endTime
                }
                axios.request({
                    url: '/tpm/andon/GetCostTimeByMachineid',
                    data,
                    method: 'post'
                }).then(result => {
                    if (result.data.ret === 1) {
                        this.optObj.andonCount = parseInt(result.data.data.andon_count)
                        this.optObj.andonTime = parseInt(result.data.data.cost_time)
                    }
                })
            })
        },
        mockTableData2 (tablelist) { // 转换数据，并赋值给列表数据容器tableData1
            let data = []
            let b = true // 如果列表中item.expection3全部有值，那么隐藏保存按钮，否则显示
            this.optObj.todayObj = []
            tablelist.forEach(item => {
                if (item) {
                    if (b && item.expection3 === '') {
                        b = false
                    }
                    if (item.expection3 === '') {
                        this.optObj.todayObj.push({
                            id: item.id,
                            expection1: item.expection1,
                            expection2: item.expection2,
                            expection3: item.expection3,
                            type: 5,
                            remark: ''
                        })
                    }
                    data.push({
                        id: item.id,
                        status: item.status,
                        expection_type: item.expection_type,
                        expection1: item.expection1,
                        expection2: item.expection2,
                        expection3: item.expection3,
                        create_time: this.changeDate(item.create_time * 1000),
                        creator: item.creator,
                        creator_name: item.creator_name,
                        handler: item.handler,
                        handler_name: item.handler_name,
                        handle_time: this.changeDate(item.handle_time * 1000),
                        complete_time: this.changeDate(item.complete_time * 1000),
                        machine: item.machine,
                        station: item.station,
                        station_name: item.station_name,
                        process_code: item.process_code,
                        projectid: item.projectid,
                        is_shutdown: item.is_shutdown,
                        approve_time: item.approve_time,
                        andon_cost_time: item.andon_cost_time,
                        handle_cost_time: item.handle_cost_time
                    })
                }
            })
            this.optObj.hasVal = b
            this.tableData2 = data
        },
        saveAndon () { // 保存安灯
            if (this.optObj.todayObj.length > 0) {
                let valid = true
                let msg = ''
                this.optObj.todayObj.forEach((item, i) => {
                    if (item.expection3 === 0 || item.expection3 === '' || item.expection3 === undefined) {
                        valid = false
                        return false
                    }
                })
                if (!valid) {
                    alert(this.$t(7000045))
                    return false
                }
                this.optObj.todayObj.forEach((item, i) => {
                    let data = {
                        id: item.id,
                        expection: item.expection3, // --异常类型id（处理完成后填写）
                        type: item.type, // 3：签到/4：处理完成/5：确认
                        remark: item.remark
                    }
                    axios.request({
                        url: '/tpm/Andon/HandleAndon',
                        data,
                        method: 'post'
                    }).then(res => {
                        if (res.data.ret === 0) { // res.data.ret === 0
                            console.log('第' + i + '条数据保存失败，原因：' + res.data.msg + ';')
                        }
                    })
                })
            }
        },
        handleExpectionlevelchange (value, selectedData) {
            this.expectionLeveldata = value
        },
        getTime (data) {
            let s = ''
            let hours = parseInt((data % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
            let minutes = parseInt((data % (1000 * 60 * 60)) / (1000 * 60))
            s = (hours < 10 ? ('0' + hours) : hours) + ':' + (minutes < 10 ? ('0' + minutes) : minutes)
            return s
        },
        toExcel () { // 导出excel
            let data = {
                value_type: this.filterObj.valueType,
                severity_level: this.filterObj.import,
                instruction_cycle: this.filterObj.instructionCycle,
                department: this.filterObj.department,
                person: this.filterObj.user,
                modeType: this.filterObj.modeType,
                datetype: this.filterObj.dateRang,
                sectionid: this.levelid
            }
            axios.request({
                url: '/tpm/Plan/exportAll',
                data,
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1) {
                    window.location.href = axios.publicPath + '' + res.data.data
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        },
        loadexcel () {
            axios.request({
                url: '/tpm/Plan/GetTemplateSkf',
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1) {
                    window.location.href = axios.publicPath + '' + res.data.data
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        },

        changeDate (dateA) {
            var dateee = new Date(dateA).toJSON()
            var date = new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(
                /\.[\d]{3}Z/,
                '').replace(/\//g, '-')
            return date
        }

    },
    watch: {

    }
}
</script>
<style lang="less" scoped>

</style>
