<template>
  <div class="testdiv">
    <div class="divborder newSearchDiv" style="margin:0px;">
        <div class="filter">
          <label>{{$t('100088')}}：</label>
           <!-- <Select v-model="productname" label-in-value filterable clearable  remote
                :remote-method="remoteMethod"
                :loading="loading1" class="searchSelect" >
              <Option v-for="item in products" :value="item.id" :key="item.id">{{ item.name }}({{item.code}})</Option>
          </Select> -->
          <Select v-model="productname" label-in-value filterable clearable
                :loading="loading1" class="searchSelect" >
              <Option v-for="item in products" :value="item.id" :key="item.id">{{ item.name }}({{item.code}})</Option>
          </Select>
        </div>
         <div class="searchBtn">
          <Button type="primary" class="twoWord" icon="ios-search" @click="search(1,10)">{{$t('1001')}}</Button>
          <Button type="success" class="twoWord" icon="md-add-circle" @click="add()">{{$t('1002')}}</Button>
          <Button type="error" class="twoWord intervalRight" icon="md-close-circle" @click="dele()">{{$t('1004')}}</Button>
          <Button type="primary" class="fourWord" icon="md-download" @click="loadexcel()">{{$t('1005')}}</Button>
           <Upload style="display:inline-block"
            ref="upload"
            :action="action"
            name="excel-file"
            :headers="headers"
            :show-upload-list="false"
            :on-format-error="handleFormatError"
            :on-success="handleSuccess"
            :on-error="handleError"
            :format ="['xlsx']">
         <Button type="primary" class="fourWord" icon="md-cloud-upload">{{$t('1006')}}</Button>
        </Upload>
         </div>
    </div>
    <div class="divborder newTableDiv">
      <Table
         class="tableClass"
        @on-current-change="handleRowChange"
        highlight-row
        :data="tableData1"
        @on-selection-change="handleSelectRow"
        :columns="tableColumns1"></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>
     <Modal class="newModalClass" :title="$t('900877')" v-model="addmodal" :styles="{width:'730px'}">
        <div class="modal_body newTableDiv">
        <div style="height:300px; overflow-x:hidden;overflow-y:auto; margin-bottom:10px;margin-right:40px;">
         <Table highlight-row
          :data="tableData2"
          @on-current-change="handleRowChange2"
          :columns="tableColumns2">
        </Table></div>
        <div class="filter">
            <label>{{this.$t('6000029')}}：</label>
            <Input class="searchInput" disabled type="text" v-model="addobj.serialnumber"/>
        </div>
        <div class="filter">
            <label><i>*</i>{{this.$t('900967')}}：</label>
            <Input class="searchInput" type="text" v-model="addobj.name"/>
        </div>
        <div class="filter">
            <label><i>*</i>{{this.$t('6000030')}}：</label>
            <Input class="searchInput" type="text" v-model="addobj.description"/>
        </div>
        <div class="filter">
            <label>{{this.$t('6000031')}}(min)：</label>
            <Input class="searchInput" type="number" min=0 v-model="addobj.workinghours"/>
        </div>
         <div class="filter">
            <label>{{this.$t('6000035')}}(min)：</label>
            <Input class="searchInput" type="number" min=0  v-model="addobj.prepare"/>
        </div>
      </div>
      <div slot="footer">
            <Button type="text" size="large" @click="closeadd()">{{$t('1033')}}</Button>
            <Button type="primary" size="large" @click="savedata()">{{$t('900306')}}</Button>
            <Button type="error" size="large" @click="deldata()">{{$t('1004')}}</Button>
            <Button type="primary" size="large" @click="submit()">{{$t('1027')}}</Button>
        </div>
      </Modal>
    </div>
  </div>
</template>
<script>
import axios from '@/libs/api.request'
export default {
    name: 'routemanagement', // 组件不刷新
    data () {
        return {
            action: axios.publicPath + 'config/upload/submit?templateName=RouteList',
            headers: {
                token: localStorage.getItem('token'),
                timestamp: localStorage.getItem('timestamp'),
                nonce: localStorage.getItem('nonce'),
                sign: localStorage.getItem('sign')
            },
            products: [],
            productname: '',
            machinetypes: [],
            tableData1: [],
            tableData2: [],
            total: 0,
            page: 1,
            pagesize: 10,
            addmodal: false,
            addobj: [],
            detailobj: {},
            selectids: '',
            serialnumberNo: 1,
            loading1: false, // 远程搜索loading
            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: '70px'
                },
                {
                    title: this.$t('100088'),
                    key: 'productname'
                },
                {
                    title: this.$t('100089'),
                    key: 'productcode'
                },
                {
                    title: this.$t('900579'),
                    key: 'serialnumber',
                    width: '90px'
                },
                {
                    title: this.$t('900967'),
                    key: 'name'
                },
                {
                    title: this.$t('6000030'),
                    key: 'description'
                },
                {
                    title: this.$t('6000031'),
                    key: 'working_hours'
                },
                {
                    title: this.$t('6000035'),
                    key: 'prepare'
                },
                {
                    title: this.$t('500030'),
                    key: 'addtime',
                    width: '150px'
                },
                {
                    title: this.$t('100008'),
                    key: 'create_username'
                }
            ],
            tableColumns2: [
                {
                    type: 'index',
                    title: this.$t('6000029'),
                    key: 'serialnumber',
                    width: '90px'
                },
                {
                    title: this.$t('900967'),
                    key: 'name',
                    tooltip: true,
                    width: '90px'
                },
                {
                    title: this.$t('6000030'),
                    tooltip: true,
                    key: 'description'
                },
                // {
                //   title: this.$t('100074'),
                //   key: 'machinetypename'
                // },
                {
                    title: this.$t('6000031'),
                    key: 'workinghours',
                    tooltip: true,
                    width: '90px'
                },
                {
                    title: this.$t('6000035'),
                    key: 'prepare',
                    tooltip: true,
                    width: '90px'

                }
            ]
        }
    },
    created () {
        this.iniproducts('')
        this.search(1, 10)
        // 格式化表格样式
        this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1)
    },
    methods: {
        handleFormatError (file) {
            this.$Message.error(this.$t('950396') + file.name + this.$t('950397'))
        },
        handleSuccess (res, file) {
            if (res.ret == 1) {
                this.$Message.success(this.$t('950398'))
                this.search(this.page, this.pagesize)
            } else {
                if ((res.msg + '').indexOf(',') != -1) {
                    inittip(res.msg)
                } else {
                    this.$Message.error(this.$t(res.msg))
                }
            }
        },
        handleError () {
            this.$Message.error(this.$t('2010006') + '!')
        },
        // remoteMethod (query) { // 远程搜索
        //   console.log(333333)
        //   console.log(query)
        //   if (query !== '') {
        //     this.loading1 = true
        //     setTimeout(() => {
        //       this.loading1 = false
        //       this.iniproducts(query)
        //     }, 200)
        //   } else {
        //     this.iniproducts('')
        //   }
        // },
        iniproducts (query) {
            var params = {
                name: query,
                count: 1000000
            }
            axios
                .request({
                    url: '/config/ProjectProduct/GetProductsByCode',
                    params,
                    method: 'get'
                })
                .then(res => {
                    this.products = res.data.data
                })
        },
        search (page, pagesize) {
            var params = {
                productId: this.productname,
                page: page,
                pagesize: pagesize
            }
            axios
                .request({
                    url: '/config/ProductRoute/GetPagedRoutes',
                    params,
                    method: 'get'
                })
                .then(res => {
                    this.total = res.data.total
                    this.page = res.data.page
                    this.mockTableData1(res.data.data)
                })
        },
        mockTableData1 (tablelist) {
            let data = []
            tablelist.forEach(item => {
                if (item) {
                    data.push({
                        productname: item.productname,
                        productcode: item.productcode,
                        serialnumber: item.serialnumber,
                        name: item.name,
                        description: item.description,
                        working_hours: item.working_hours,
                        prepare: item.prepare,
                        addtime: item.addtime,
                        create_username: item.create_username,
                        id: item.id
                    })
                }
            })
            this.tableData1 = data
        },
        handleSelectRow: function (data) {
            var ids = []
            for (var i in data) {
                ids.push(data[i].id)
            }
            this.selectids = ids.join(',')
        },
        handleRowChange (currentRow, oldCurrentRow) {
            this.detailobj = currentRow
        },
        handlePageSize (value) {
            this.pagesize = value
            this.search(this.page, this.pagesize)
        },
        changePage (value) {
            this.page = value
            this.search(this.page, this.pagesize)
        },
        add () {
            if (this.productname === undefined || this.productname === '') {
                this.$Message.error(this.$t('100217'))
                return false
            }
            // 检查是否已经存在工序
            axios.request({
                url: '/config/ProductRoute/GetRoutesByProduct?productId=' + this.productname,
                method: 'get'
            })
                .then(res => {
                    if (res.data.data.length > 0) {
                        this.$Message.error(this.$t('9000423'))
                        return false
                    } else {
                        this.addmodal = true
                        this.iniaddobj()
                        this.inimachinetype()
                    }
                })
        },
        change (value) {
            if (value !== undefined) {
                this.addobj.machinetypename = value.label
            }
        },
        iniaddobj () {
            this.addobj = {
                serialnumber: this.serialnumberNo,
                name: '',
                description: '',
                machinetypename: '',
                machinetype: 0,
                workinghours: 0,
                prepare: 0
            }
        },
        inimachinetype () {
            axios.request({
                url: '/config/MachineType/GetParentChildTypes',
                method: 'get'
            })
                .then(res => {
                    this.machinetypes = res.data.data
                })
        },
        closeadd () {
            this.addmodal = false
        },
        savedata () {
            if (this.addobj.serialnumber === undefined || this.addobj.serialnumber === '') {
                this.$Message.error(this.$t('6000032'))
                return false
            }
            if (this.addobj.name === undefined || this.addobj.name === '') {
                this.$Message.error(this.$t('100042'))
                return false
            }
            if (this.addobj.description === undefined || this.addobj.description === '') {
                this.$Message.error(this.$t('6000034'))
                return false
            }
            // if (this.addobj.machinetype === undefined || this.addobj.machinetype === 0) {
            //   this.$Message.error(this.$t('100180'))
            //   return false
            // }
            if (this.addobj.workinghours === undefined || this.addobj.workinghours === 0) {
                this.$Message.error(this.$t('6000033'))
                return false
            }
            // 修改还是添加
            var index = -1
            for (var i = 0; i < this.tableData2.length; i++) {
                if (this.tableData2[i].serialnumber === this.addobj.serialnumber) {
                    index = i
                    this.serialnumberNo = this.tableData2.length + 1
                }
            }
            if (index === -1) {
                this.serialnumberNo += 1
                this.tableData2.push(this.addobj)
            } else {
                this.tableData2[index].serialnumber = index + 1
                this.tableData2[index].name = this.addobj.name
                this.tableData2[index].description = this.addobj.description
                // this.tableData2[index].machinetype = this.addobj.machinetype
                this.tableData2[index].machinetypename = this.addobj.machinetypename
                this.tableData2[index].workinghours = this.addobj.workinghours
                this.tableData2[index].prepare = this.addobj.prepare
            }
            this.iniaddobj()
        },
        handleRowChange2 (currentRow, oldCurrentRow) {
            this.addobj = currentRow
        },
        deldata () {
            var index = -1
            for (var i = 0; i < this.tableData2.length; i++) {
                if (this.tableData2[i].name === this.addobj.name) {
                    index = i
                }
            }
            if (index > -1) {
                this.tableData2.splice(index, 1)
                for (var i = 0; i < this.tableData2.length; i++) {
                    this.tableData2[i].serialnumber = i + 1
                }
                this.serialnumberNo = this.tableData2.length + 1
                this.iniaddobj()
            } else {
                this.$Message.error(this.$t('900777'))
            }
        },
        submit () {
            this.$Modal.confirm({
                title: this.$t('900495'),
                content: '',
                closable: true,
                okText: this.$t('1011'),
                onOk: () => {
                    let routes = []
                    for (var i in this.tableData2) {
                        var item = this.tableData2[i]
                        let route = {}
                        route.route_ordernumber = item.serialnumber
                        route.route_name = item.name
                        route.description = item.description
                        route.machine_type = 0
                        route.hours = item.workinghours
                        route.prepare = item.prepare
                        routes.push(route)
                    }
                    if (routes === [] || routes.length === 0) {
                        this.$Message.error(this.$t('4000003'))
                        return false
                    }
                    let data = {
                        productid: this.productname,
                        routes: routes
                    }
                    axios.request({
                        url: '/config/ProductRoute/AddRoute',
                        data,
                        method: 'post'
                    }).then(res => {
                        if (res.data.ret === 1) {
                            this.$Message.success(this.$t('1055'))
                            this.page = 1
                            this.search(this.page, this.pagesize)
                            this.addmodal = false
                            this.tableData2 = []
                            this.serialnumberNo = 1
                        } else {
                            this.$Message.error(this.$t(res.data.msg))
                        }
                    })
                }
            })
        },
        dele () {
            if (this.selectids === undefined || this.selectids === '') {
                this.$Message.error((this.$t('1017')))
                return false
            } else {
                this.$Modal.confirm({
                    title: this.$t('1018'),
                    content: '',
                    width: '290px',
                    closable: true,
                    okText: this.$t('1004'),
                    onOk: () => {
                        axios.request({
                            url: '/config/ProductRoute/DeleteRoute?ids=' + this.selectids,
                            method: 'get'
                        }).then(res => {
                            if (res.data.ret === 1) {
                                this.$Message.success(this.$t('1058'))
                                this.page = 1
                                this.search(this.page, this.pagesize)
                                this.detailobj = {}
                            } else {
                                this.$Message.error(this.$t(res.data.msg))
                            }
                        })
                    }
                })
            }
        },
        loadexcel () {
            axios.request({
                url: '/config/download/GetTemplate?name=RouteList',
                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))
                }
            })
        }

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