<template>
  <div class="testdiv">
    <!-- 工艺路由设置 -->
    <div class="divborder newSearchDiv" style="margin:0px;">
        <!-- 产线层级 -->
      <div class="filter">
          <label >{{$t('1132')}}：</label>
          <Cascader :data="datalevel" :value="leveldata" @on-change="handlelevelchange" trigger="click" change-on-select class="searchSelect"></Cascader>
      </div>
      <div class="filter">
        <label>{{$t('100088')}}：</label>
        <Select v-model="productname" label-in-value clearable @on-change="changeProduct" filterable class="searchSelect">
          <Option
            v-for="(item,index) in products"
            :value="item.name"
            :key="index"
            :tag="index"
          >{{ item.name }}({{item.code}})</Option>
        </Select>
      </div>
      <div class="searchBtn">
        <Button type="primary" class="twoWord" icon="ios-search" @click="tosearch()">{{$t('1001')}}</Button>
        <Button type="success" class="twoWord" icon="md-add-circle" @click="add()">{{$t('1002')}}</Button>
        <Button type="warning" class="twoWord" icon="ios-create-outline" @click="edit()">{{$t('1003')}}</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>
        <Button type="primary" class="fourWord" icon="ios-cloud-download" @click="Export()">{{$t('1007')}}</Button>
      </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"
            :page-size="pagesize"
            @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" v-model="addmodal" :styles="{width:'530px'}">
        <p slot="header">
          <span v-if="type===1">{{$t('1002')}}</span>
          <span v-if="type===2">{{$t('1003')}}</span>
        </p>
        <div class="modal_body">
          <div class="filter">
            <label><i>*</i>{{$t('100088')}}：</label>
            <Select
              v-model="productname1"
              label-in-value
              filterable
              clearable
              class="searchSelect"
              @on-change="productChange"
              :disabled="disabledValue"
            >
              <Option
                v-for="(item,index) in products"
                :value="item.name"
                :key="index"
                :tag="index"
              >{{ item.name }}({{item.code}})</Option>
            </Select>
          </div>
          <div class="filter">
            <label><i>*</i>{{$t('950217')}}：</label>
            <Select v-model="routename1" label-in-value filterable clearable class="searchSelect" :disabled="disabledValue">
              <Option v-for="(item,index) in routenames" :value="item.id" :key="index">{{ item.name }}</Option>
            </Select>
          </div>
          <!-- 当前产线层级 -->
          <div class="filter">
            <label><i>*</i>{{$t('900997')}}：</label>
            <Cascader :data="datalevel" :value="leveldata1" @on-change="handlelevelchange1" trigger="click" :disabled="disabledValue" change-on-select class="searchSelect MaxWidth"></Cascader>
          </div>
          <!-- 上一产线层级 -->
          <div class="filter">
            <label><i>*</i>{{$t('950214')}}：</label>
            <Cascader :data="datalevel" :value="leveldata2" @on-change="handlelevelchange2" trigger="click" change-on-select class="searchSelect MaxWidth"></Cascader>
          </div>
          <div class="filter">
            <label><i>*</i>{{this.$t('800195')}}：</label>
            <Select v-model="resultname1" label-in-value clearable class="searchSelect">
              <Option
                v-for="(item,index) in results"
                :value="item.eventNo"
                :key="index"
              >{{ item.descr }}</Option>
            </Select>
          </div>
        </div>
        <div slot="footer">
          <Button type="text" size="large" @click="addmodal=false">{{$t('1033')}}</Button>
          <Button type="primary" v-if="type===1" size="large" @click="addPost(1)">{{$t('1002')}}</Button>
          <Button type="primary" v-if="type===2" size="large" @click="addPost(2)">{{$t('1003')}}</Button>
        </div>
      </Modal>
    </div>
  </div>
</template>
<script>
import axios from '@/libs/api.request'
export default {
    data () {
        return {
            action:axios.publicPath +'/acc/Upload/UploadExcel?templateName=RoutingstationInfo',
            headers: {
                token: localStorage.getItem('token'),
                timestamp: localStorage.getItem('timestamp'),
                nonce: localStorage.getItem('nonce'),
                sign: localStorage.getItem('sign')
            },
            products: [], //产品列表
            productname: '', //产品名称
            productcode:'',
            leveldata: [],//选中产线层级数组
            datalevel: [],//产线层级树菜单
            sectionid:0, //选中工位
            levelCount:0, //产线层级层数

            //弹窗
            productname1:'',//产品名称
            productcode1:'',//产品编号
            routename1:'',//工艺名称
            routenames: [],
            //当前产线层级
            leveldata1: [],//选中产线层级数组
            sectionid1:0, //选中工位
            //上一产线层级
            leveldata2: [],//选中产线层级数组
            sectionid2:0, //选中工位
            resultname1:'',//结果
            results: [],
            tableData1: [],
            total: 0,
            page: 1,
            pagesize: 10,
            addmodal: false,
            detailobj: '',
            type: 0,
            disabledValue:false,
            tableColumns1: [
                {
                    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('950213'),
                    key: 'process_Seq'
                },
                {
                    title: this.$t('900967'),
                    key: 'process_Name'
                },
                {
                    title: this.$t('900879'),
                    key: 'line'
                },
                {
                    title: this.$t('900997'),
                    key: 'station'
                },
                {
                    title: this.$t('950214'),
                    key: 'fromStation'
                },
                {
                    title: this.$t('950215'),
                    key: 'result'
                }
            ]
        }
    },
    created () {
        this.initlevel();//产线层级
        this.iniproducts()
        this.tosearch()
        this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1)
    },
    methods: {
        //获取产线层级树结构数据
        initlevel () {
            axios.request({
                url: '/config/ProjectLevelSection/GetSectionTree',
                method: 'get'
            }).then(res => {
                const arr = []
                this.datalevel = res.data.data
                this.leveldata = arr

                //查询产线层级层数
                this.levelCount = this.getlevelCount(res.data.data);
            })
        },
        //查询产线层级层数
        getlevelCount(data){
            let count = 0;
            initCount(data);
            function initCount(data){
                if(Array.isArray(data)&&data.length > 0){
                    count += 1;
                    data.forEach((item,index)=>{
                        initCount(item.children);
                    })
                }
            }
            return count;
        },
        handlelevelchange (value) {
            this.leveldata = value
            this.sectionid = 0
            if(value!=undefined&&Array.isArray(value)&&value.length >0){
                this.sectionid = value[value.length - 1];
            }
        },
        handlelevelchange1 (value) {
            this.leveldata1 = value
            this.sectionid1 = 0
            if(value!=undefined&&Array.isArray(value)&&value.length >0){
                this.sectionid1 = value[value.length - 1];
            }
        },
        handlelevelchange2 (value) {
            this.leveldata2 = value
            this.sectionid2 = 0
            if(value!=undefined&&Array.isArray(value)&&value.length >0){
                this.sectionid2 = value[value.length - 1];
            }
        },
        //获取产品
        iniproducts () {
            var params = {
                page: 1,
                pagesize: 9999999
            }
            axios.request({
                url: '/config/ProjectProduct/GetProductItems',
                params,
                method: 'get'
            })
            .then(res => {
                let data = res.data.data;
                this.products = []
                if(res.data.ret === 1&&Array.isArray(data)&&data.length >0){
                    this.products = data;
                }
            })
        },
        changeProduct(value){
            this.productcode = '';
            if(value!=undefined){
                let index = value.tag;
                this.productcode = this.products[index].code;
            }
        },
        //切换产品,获取工艺信息
        productChange(value){
            this.productcode1 = '';
            let pid = 0;
            if(value!=undefined){
                let index = value.tag;
                this.productcode1 = this.products[index].code;
                pid = this.products[index].id;
            }
            this.getRoutes(pid);
        },
        getRoutes(pid){
            var params = {
                productId:pid
            }
            axios.request({
                url: '/config/ProductRoute/GetRoutesByProduct',
                params,
                method: 'get'
            })
            .then(res => {
                let data = res.data.data;
                this.routenames = []
                if(res.data.ret === 1&&Array.isArray(data)&&data.length >0){
                    this.routenames = data;
                }
            })
        },
        //结果
        initresults(){
            axios.request({
                url: '/acc/Routing/GetResultData',
                method: 'get'
            })
            .then(res => {
                let data = res.data.data;
                this.results = []
                if(res.data.ret === 1&&Array.isArray(data)&&data.length >0){
                    this.results = data;
                }
            })
        },
        add () {
            this.productname1='',//产品名称
            this.productcode1='',//产品编号
            this.routename1='',//工艺名称
            //当前产线层级
            this.leveldata1 = []
            this.sectionid1=0, //选中工位
            //上一产线层级
            this.leveldata2 = []
            this.sectionid2=0, //选中工位
            this.resultname1='',//结果
            this.initresults()
            this.type = 1
            this.disabledValue = false
            this.addmodal = true
        },
        edit () {
            if (this.detailobj===''||!this.detailobj||this.detailobj.id == undefined) {
                this.$Message.error(this.$t('1017'))
                return false
            }
            this.initresults();
            this.productcode1 = this.detailobj.productCode; //产品编号
            this.productname1 = this.detailobj.productName;//产品名称
            this.getRoutes(this.detailobj.productid);
            this.routename1 = this.detailobj.process_Id;//工序名称
            this.resultname1 = this.detailobj.eventNo;//结果
            //当前工资
            this.sectionid1 = this.detailobj.stationId;
            this.leveldata1 = this.getChecklevel(this.sectionid1);
            //上一工站
            this.sectionid2 = this.detailobj.fromStationId;
            this.leveldata2 = this.getChecklevel(this.sectionid2);

            this.type = 2
            this.addmodal = true
            this.disabledValue = true
        },
        //默认选中产线层级
        getChecklevel(sectionid){
            let arr = [];
            let count = -1;
            initCheck(this.datalevel);
            function initCheck(data){
                if(Array.isArray(data)&&data.length >0){
                count += 1;
                for(var i=0;i<data.length;i++){
                    if(data[i].value){
                    arr[count] = data[i].value
                    }
                    if(data[i].value === sectionid){
                    return 
                    }
                    else{
                    initCheck(data[i].children);
                    }
                }
                }
            }
            return arr;
        },
        //添加、编辑提交
        addPost(type){
            if(this.productname1===''||this.productname1===undefined){
                this.$Message.error(this.$t('100064'));
                return false;
            }
            if(this.routename1===''||this.routename1===undefined){
                this.$Message.error(this.$t('950463'));
                return false;
            }
            if(this.sectionid1===0||this.sectionid1===undefined){
                this.$Message.error(this.$t('950461'));
                return false;
            }
            if(this.leveldata1 && this.leveldata1.length != this.levelCount){
                this.$Message.error('当前工位请选择最后一层级');
                return false;
            }
            if(this.sectionid2===0||this.sectionid2===undefined){
                this.$Message.error(this.$t('950460'));
                return false;
            }
            if(this.leveldata2 && this.leveldata2.length != this.levelCount){
                this.$Message.error('上一工位请选择最后一层级');
                return false;
            }
            if(this.resultname1===''||this.resultname1===undefined){
                this.$Message.error(this.$t('950462'));
                return false;
            }
            let url='';
            let id=0
            if(type===1){
                url='/acc/Routing/AddData';
                id=0
            }
            else{
                url='/acc/Routing/ModifyData';
                id=this.detailobj.id
            }
            let data = {
                id:id,
                productCode:this.productcode1,
                productName:this.productname1,
                processId:this.routename1,
                line:0,
                fromStation:this.sectionid1,
                toStation:this.sectionid2,
                eventNo:this.resultname1,
            }
            axios.request({
                url: url,
                data,
                method: 'post'
            })
            .then(res => {
                if (res.data.ret === 1) {
                    this.addmodal = false
                    if(type===1){
                        this.$Message.success(this.$t('1055'))
                        this.tosearch();
                    }
                    else{
                        this.$Message.success(this.$t('1060'))
                        this.search()
                    }
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        },
        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'))
            } else {
                if ((res.msg + '').indexOf(',') != -1) {
                    inittip(res.msg)
                } else {
                    this.$Message.error(this.$t(res.msg))
                }
            }
        },
        handleError () {
            this.$Message.error(this.$t('2010006') + '!')
        },
        handleSelectRow: function (data) {
            var ids = []
            for (var i in data) {
                ids.push(data[i].id)
            }
            this.selectids = ids.join(',')
        },
        tosearch(){
            this.page = 1;
            this.pagesize = 10
            this.search()
        },
        search () {
            var data = {
                productCode:this.productcode,
                productName:this.productname,
                line: 0,
                toStation: this.sectionid,
                page: this.page,
                pagesize: this.pagesize
            }
            this.detailobj = '';
            axios.request({
                url: '/acc/Routing/GetData',
                data,
                method: 'post'
            })
            .then(res => {
                let data = res.data.data;
                this.total = 0
                this.tableData1 = []
                if(res.data.ret===1 && Array.isArray(data)&&data.length >0){
                    this.total = res.data.total
                    this.tableData1 = data
                }
            })
        },
        handleRowChange (currentRow, oldCurrentRow) {
            this.detailobj = currentRow
        },
        handlePageSize (value) {
            this.pagesize = value
            this.search()
        },
        changePage (value) {
            this.page = value
            this.search()
        },
        dele () {
            if (
                this.detailobj === undefined ||this.detailobj.id === undefined ||this.detailobj.id === 0
            ) {
                this.$Message.error(this.$t('1017'))
                return false
            } else {
                var data = {
                    Id: this.detailobj.id,
                    resultStatus: this.detailobj.resultStatus
                }
                this.$Modal.confirm({
                    title: this.$t('1018'),
                    content: '',
                    width: '290px',
                    closable: true,
                    okText: this.$t('1004'),
                    onOk: () => {
                        axios.request({
                            url: '/acc/Routing/DeleteData',
                            data,
                            method: 'post'
                        })
                        .then(res => {
                            if (res.data.ret === 1) {
                                this.$Message.success(this.$t('1058'))
                                this.detailobj = ''
                                this.search()
                            } else {
                                this.$Message.error(this.$t(res.data.msg))
                            }
                        })
                    }
                })
            }
        },
        loadexcel () {
            axios
                .request({
                    url: '/config/download/GetTemplate?name=RoutingstationInfo',
                    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))
                    }
                })
        },
        Export () {
            let data = {
                productCode:this.productcode,
                productName:this.productname,
                line: 0,
                toStation: this.sectionid,
                page: this.page,
                pagesize: this.pagesize
            }
            axios.request({
                url: '/acc/Routing/ExportData',
                data,
                method: 'post'
            })
            .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>
