<template>
    <div>
        <div class="divborder newSearchDiv">
            <div class="filter">
                <label>{{ $t(8070) }}：</label>
                <Select v-model="warehouseid" label-in-value clearable filterable filter-by-label @on-change="changeWarehouse" class="searchSelect">
                    <Option
                    v-for="(item,index) in whdata"
                    :value="item.id"
                    :key="index"
                    :label="item.name"
                    >{{ item.name }}</Option>
                </Select>
            </div>
            <div class="filter">
                <label>{{ $t(5500316) }}：</label>
                <Cascader class="searchSelect" :data="storageTree" clearable change-on-select @on-change="changeStorage"></Cascader>
            </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','xls']"
                >
                    <Button
                        type="primary"
                        class="fourWord"
                        icon="md-cloud-upload"
                    >{{$t('1006')}}</Button>
                </Upload>
                <Button type="primary" class="fourWord" icon="ios-cloud-download" @click="search(1)">{{$t('1007')}}</Button>
            </div>
        </div>
        <div class="divborder newTableDiv">
            <Table
                class="tableClass"
                @on-current-change="handleRowChange"
                highlight-row
                :data="tableData1"
                :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>
        </div>

        <Modal class="newModalClass" v-model="addmodal" :styles="{width:'650px'}">
            <p slot="header">
                <span v-show="type==1">{{$t('1002')}}</span>
                <span v-show="type==2">{{$t('1003')}}</span>
            </p>
            <div class="demo-spin-col">
                <Spin fix  v-if="spinShow">
                    <div>正在上传...</div>
                </Spin>
                <div class="filter">
                    <label><i>*</i>{{ $t(8070) }}：</label>
                    <Select v-model="addwarehouseid" label-in-value clearable filterable filter-by-label @on-change="changeWarehouse1" class="searchSelect">
                        <Option
                        v-for="(item,index) in whdata"
                        :value="item.id"
                        :key="index"
                        :label="item.name"
                        >{{ item.name }}</Option>
                    </Select>
                </div>
                <div class="filter">
                    <label><i>*</i>{{ $t(5500316) }}：</label>
                    <Cascader class="searchSelect" :data="addstorageTree" v-model="addstorageList" clearable change-on-select @on-change="changeStorage1"></Cascader>
                </div>
                <div class="filter">
                    <label><i>*</i>工装类型：</label>
                    <Cascader class="searchSelect" :data="frockTypeTree" v-model="parentType" change-on-select @on-change="changeFrockType1"></Cascader>
                </div>
                <div class="filter">
                    <label><i>*</i>工装名称：</label>
                    <Select v-model="addfrockid" label-in-value clearable filterable filter-by-label class="searchSelect">
                        <Option
                        v-for="(item,index) in addfrockList"
                        :value="item.id"
                        :key="index"
                        :label="item.name+'#'+item.code"
                        >{{ item.name+'#'+item.code }}</Option>
                    </Select>
                </div>
                <div class="filter">
                    <label>备注：</label>
                    <Input type="text" class="searchInput" v-model="addremark" />
                </div>
                <div>
                    <label>上传文件：</label>
                    <div class="accountInfoUploadFile">
                        <Upload
                            ref="upload"
                            :show-upload-list="false"
                            :on-success="handleSuccess1"
                            :before-upload="handleBeforeUpload"
                            :on-error="handleError1"
                            type="drag"
                            :headers="headers"
                            :action="UploadAction">
                            <div class="descicon" style="">
                                <Icon type="md-cloud-upload" size="15"></Icon>
                                <span>上传文件</span>
                            </div>
                        </Upload>
                        <div v-show="filename" class="hasfile">{{filename}}<Icon @click.native="delfile" type="ios-close-circle" size="15" /></div>
                    </div>
                </div>
            </div>
            <div slot="footer">
                <Button type="text" size="large" @click="addmodal=false">{{$t('1033')}}</Button>
                <Button type="primary" size="large" @click="addPost()">{{$t('1011')}}</Button>
            </div>
        </Modal>

    </div>
</template>
<script>
export default {
    data(){
        return{
            whdata:[],//仓库列表
            warehouseid:"",//仓库id
            //储位
            storageTree:[],
            storageid:"",//储位id

            //列表
            total:0,
            page:1,
            pagesize:10,
            tableData1:[],
            tableColumns1:[
                {
                    type: "index2",
                    title: this.$t("1008"),
                    key: "xuhao",
                    render: (h, params) => {
                        return h(
                            "span",
                            params.index + (this.page - 1) * this.pagesize + 1
                        );
                    },
                },
                {
                    title:'仓库名称',
                    key:'wavehouse'
                },
                {
                    title:'储位信息',
                    key:'location'
                },
                {
                    title:'储位ID',
                    key:'locaid'
                },
                {
                    title:'工装类别',
                    key:'category'
                },
                {
                    title:'工装编号',
                    key:'code'
                },
                {
                    title:'工装名称',
                    key:'fixturetool'
                },
                {
                    title:'工装规格',
                    key:'specfication'
                },
                {
                    title:'工件编号',
                    key:'sn'
                },
                {
                    title:'工序顺序',
                    key:'routenumber'
                },
                {
                    title:'工序名称',
                    key:'route'
                },
                {
                    title:'物料状态',
                    key:'materialstate',
                    render:(h,params)=>{
                        let str = '';
                        //materialstate:1:有工装无工件2:有工装有工件3:无工装无工件4:无工装有工件
                        if(params.row.materialstate===1){
                            str = '有工装无工件';
                        }else if(params.row.materialstate===2){
                            str = '有工装有工件';
                        }else if(params.row.materialstate===2){
                            str = '无工装无工件';
                        }else if(params.row.materialstate===2){
                            str = '无工装有工件';
                        }
                        return h('span',str);
                    }
                },
                {
                    title:'备注',
                    key:'remark'
                },
                {
                    title:'附件',
                    key:'filename',
                    render:(h,params)=>{
                        return h('span',{
                            style:{
                                color:'#2b85e4',
                                cursor:'pointer'
                            },
                            on:{
                                click:()=>{
                                    let name = params.row.filename;
                                    let url = params.row.fileurl;
                                    if(url){
                                        this.downFile(url,name);
                                    }
                                }
                            }
                        },params.row.filename);
                    }
                },
                {
                    title:'维护人',
                    key:'updator'
                },
                {
                    title:'维护时间',
                    key:'updatetime'
                }
            ],

            //弹窗
            addmodal:false, //添加弹窗
            addwarehouseid:'',//仓库id
            type:1,
            addstorageTree:[],//储位列表
            addstorageList:[],
            addstorageid:'',//储位id
            storagelevelnum:0,//储位层级数

            frockTypeTree:[],//工装类型
            parentType:[],
            addfrockList:[],//工装列表
            addfrockid:'',//工装名称
            addremark:'',//备注
            filename:'',
            fileurl:'',
            action: this.axios.publicPath + "acc/Upload/Submit?templateName=AutomationLocationTemplate",
            UploadAction: this.axios.publicPath + "config/upload/UploadImage",
            headers: {
                token: localStorage.getItem("token"),
                timestamp: localStorage.getItem("timestamp"),
                nonce: localStorage.getItem("nonce"),
                sign: localStorage.getItem("sign"),
            },
            spinShow:false,
        }
        
    },
    created(){
        this.initWarehouse();//仓库
        this.initStorage();
        this.tosearch();
        this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1);
    },
    methods:{
        /*************搜索 start************ */
        //仓库下拉框
        initWarehouse(){
            let params = {
                page: 1,
                pagesize: 1000000,
                typeid: 0, // 产线层级id
                name: '',
            };
            this.axios.request({
                url: "/wms/WaveHouse/GetWaveHouseList",
                params,
                method: "get",
            })
            .then((res) => {
                this.whdata = [];
                this.whdata1 = [];
                let data = res.data.data;
                if (res.data.ret == 1&&Array.isArray(data)&&data.length) {
                    this.whdata = res.data.data;
                    this.whdata1 = res.data.data;
                }
            });
        },
        //切换仓库
        changeWarehouse(value){
            this.storageList = [];
            this.storageid = "";
            if(value != undefined){
                this.warehouseid = value.value;
                this.initStorage();
            }
        },
        //储位
        initStorage(){
            let params = {
                warehouseid: this.warehouseid,
            };
            this.axios.request({
                url: "/wms/Location/GetLocationTree",
                params,
                method: "get",
            })
            .then((res) => {
                if (res.data.ret == 1) {
                    let arr = res.data.data;
                    this.contentTree(arr);
                    this.storageTree = arr;
                }
            });
        },
        contentTree (arr) {
            arr.forEach(ele => {
                ele.disabled = false;
                ele.value = ele.id;
                ele.label = ele.name;
                if (
                    ele.children != undefined &&
                    ele.children != null &&
                    ele.children.length != 0 
                ) {
                    this.contentTree(ele.children);
                }else{
                    ele.children = []
                }
            });
        },
        //切换储位
        changeStorage(){
            this.storageid = "";
            if(value != undefined && value.length){
                this.storageid = value[value.length - 1];
            }
        },
        /*************搜索 end************ */
        /***************弹窗 start***************** */
        //弹窗-切换仓库
        changeWarehouse1(value){
            this.addstorageTree = [];
            this.addstorageid = "";
            if(value != undefined){
                this.addwarehouseid = value.value;
                this.addinitStorage();
            }
        },
        //弹窗-获取储位
        addinitStorage(){
            let params = {
                warehouseid: this.addwarehouseid,
            };
            this.axios.request({
                url: "/wms/Location/GetLocationTree",
                params,
                method: "get",
            })
            .then((res) => {
                if (res.data.ret == 1) {
                    let arr = res.data.data;
                    this.contentTree1(arr);
                    this.addstorageTree = arr;
                }
            });
        },
        contentTree1 (arr) {
            let max = 0;
            function eachfun(arr,floor){
                arr.forEach(ele => {
                    ele.disabled = false;
                    ele.value = ele.id;
                    ele.label = ele.name;
                    if (floor > max) {
                        max = floor;
                    }
                    if (
                        ele.children != undefined &&
                        ele.children != null &&
                        ele.children.length != 0 
                    ) {
                        eachfun(ele.children,floor+1);
                    }else{
                        ele.children = []
                    }
                });
            }
            eachfun(arr, 1);
            this.storagelevelnum = max;
            return arr;
        },
        //弹窗-切换储位
        changeStorage1(value){
            this.addstorageid = "";
            if(Array.isArray(value)&&value.length == this.storagelevelnum){
                this.addstorageid = value[value.length - 1];
            }
            else{
                this.addstorageList = [];
            }   
        },
        //弹窗-工装类型
        initFrockType(){
            this.axios.request({
                url: "/acc/FixtureTools/GetCategoryList",
                method: "get",
            })
            .then((res) => {
                if (res.data.ret == 1) {
                    let arr = res.data.data;
                    this.contentTree2(arr);
                    this.frockTypeTree = arr;
                }
            });
        },
        contentTree2(arr) {
            arr.forEach(ele => {
                ele.disabled = false;
                if (
                    ele.children != undefined &&
                    ele.children != null &&
                    ele.children.length != 0 
                ) {
                    this.contentTree2(ele.children);
                }else{
                    ele.children = []
                }
            });
        },
        //弹窗-工装类型变更
        changeFrockType1(value){
            this.parentTypeid = "";//工装类型清空
            this.addfrockList = [];//工装清空
            this.addfrockid = '';//工装id清空
            if(value!=undefined && value.length){
                this.parentTypeid = value[value.length - 1];
                this.getFrocksChange();
            }
        },
        //弹窗-获取工装
        getFrocksChange(){
            this.addfrockid = '';
            let params = {
                category:this.parentTypeid,//工装类型id
                code:'', 
                name:'',
                state:1, //0停用 1可用
                page:1,
                pagesize:1000000,
                toexcel:0 //0查询 1导出
            }
            this.axios.request({
                url: "/acc/FixtureTools/GetPageList",
                params,
                method: "get",
            })
            .then((res) => {
                this.addfrockList = [];
                let data = res.data.data;
                if (res.data.ret == 1 &&Array.isArray(data)&&data.length) {
                    this.addfrockList = res.data.data;
                }
            });
        },
        /***************弹窗 end***************** */
        tosearch(){
            this.page = 1;
            this.pagesize = 10;
            this.search(0);
        },
        search(toexcel){
            let params = {
                wavehouseid:this.warehouseid,//仓库id
                locationid:this.storageid,//储位id
                page:this.page,
                pagesize:this.pagesize,
                toexcel:toexcel //0查询 1导出
            }
            this.detailobj = {};
            this.axios.request({
                url: "/acc/AutomationLocation/GetPageList",
                params,
                method: "get",
            })
            .then((res) => {
                if(toexcel === 1){
                    if (res.data.ret === 1) {
                        window.location.href =
                            this.axios.publicPath + "" + res.data.data;
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                }
                else{
                    this.total = 0;
                    this.tableData1 = [];
                    let data = res.data.data;
                    if (res.data.ret == 1 &&Array.isArray(data)&&data.length) {
                        this.total = res.data.total;
                        this.tableData1 = res.data.data;
                    }
                }
            });
        },
        add(){
            this.type = 1;
            this.addwarehouseid = '';//仓库id
            this.addstorageTree = [];
            this.addstorageList = [];
            this.addstorageid = '';//储位id

            this.initFrockType();//工装类型
            this.parentType = [];//工装类型
            this.parentTypeid = '';//工装类型id

            this.addfrockid = '';//工装id
            this.addremark = '';//备注
            this.filename = '';
            this.fileurl = '';
            this.addmodal = true;
        },
        //编辑
        edit(){
            if(!this.detailobj || !this.detailobj.id){
                this.$Message.error(this.$t('1017'));
                return false;
            }
            this.type = 2;
            this.addwarehouseid = this.detailobj.wavehouseid;//仓库id
            //获取储位
            this.addinitStorage();
            this.addstorageList = this.detailobj.locationIds;
            this.addstorageid = this.detailobj.locationid;

            //获取工装类型
            this.initFrockType();//工装类型
            this.parentType = this.detailobj.categoryIds;//工装类型
            let categoryIds = this.detailobj.categoryIds;
            this.parentTypeid = this.detailobj.categoryId;
            if(Array.isArray(categoryIds)&& categoryIds.length){
                this.getFrocksChange();
            }
            this.addfrockid = this.detailobj.fixturetoolid;//工装id
            this.addremark = this.detailobj.remark?this.detailobj.remark:'';//备注
            this.filename = this.detailobj.filename;
            this.fileurl = this.detailobj.fileurl;
            this.addmodal = true;
        },
        addPost(){
            if(!this.addstorageid){
                this.$Message.error("储位信息不能为空");
                return false;
            }
            if(!this.addfrockid){
                this.$Message.error("工装名称不能为空");
                return false;
            }
            
            let url = '';
            let id = '';
            if(this.type === 1){
                url = '/acc/AutomationLocation/Add';
                id = 0;
            }
            else{
                url = '/acc/AutomationLocation/Update';
                id = this.detailobj.id;
            }
            let data = {
                id:id,
                locationid:this.addstorageid,//储位ID，前端填写的那个
                fixturetoolid:this.addfrockid,//工装ID
                fileurl:this.fileurl,//url
                filename:this.filename,//附件名称
                remark:this.addremark//备注
            }
            this.axios.request({
                url: url,
                data,
                method: "post",
            }).then((res) => {
                if (res.data.ret == 1) {
                    this.addmodal = false;
                    if(this.type===1){
                        this.tosearch();
                        this.$Message.success(this.$t('1055'));
                    }
                    else{
                        this.$Message.success(this.$t('1060'));
                        this.search(0);
                    }
                } else {
                    this.$Message.error(this.$t(res.data.msg+''));
                }
            });
        },
        //删除
        dele(){
            if (
                this.detailobj.id === undefined ||
                this.detailobj.id === null
            ) {
                this.$Message.error(this.$t("1017"));
                return false;
            } else {
                var params = {
                    id: this.detailobj.id,
                };
                this.$Modal.confirm({
                    title: this.$t("1018"),
                    content: "",
                    width: "290px",
                    closable: true,
                    okText: this.$t("1004"),
                    onOk: () => {
                        this.axios.request({
                            url: "/acc/AutomationLocation/Delete",
                            params,
                            method: "get",
                        })
                        .then((res) => {
                            if (res.data.ret === 1) {
                                this.$Message.success(this.$t("1058"));
                                this.search(0);
                            } else {
                                this.$Message.error(this.$t(res.data.msg));
                            }
                        });
                    },
                });
            }
        },
        //导出模板
        loadexcel() {
            this.axios.request({
                url: "/config/Download/GetTemplate?name=AutomationLocationTemplate",
                method: "get",
            })
            .then((res) => {
                if (res.data.ret === 1) {
                    window.location.href =
                        this.axios.publicPath + "" + res.data.data;
                } else {
                    this.$Message.error(this.$t(res.data.msg));
                }
            });
        },
        /*********文件上传 start******** */
        //下载文件 
        downFile(url,fileName){
            let params = {
                url: url,
                name:fileName
            };
            this.axios.request({
                url: "/config/Download/DownloadFileByUrl",
                params,
                method: "get",
                responseType: "blob"
            })
            .then((res) => {
                if (res.status == 200) {
                    let url;
                    let link = document.createElement("a");
                    url = window.URL.createObjectURL(res.data);
                    link.style.display = "none";
                    link.href = url;
                    link.setAttribute("download", fileName);
                    document.body.appendChild(link);
                    link.click();
                }
            }).catch(error=>{
                this.$Message.error('请求错误')
            });
        },
        handleBeforeUpload(file){
            this.spinShow = true;
            if(!file){
                this.spinShow = false;
                return false;
            }
        },
        handleSuccess1 (res,file) {
            this.spinShow = false;
            if (res.ret == 1) {
                this.$Message.success(this.$t("100378"));
                this.filename = file.name;
                this.fileurl = res.data;
            } else {
                this.$Message.error(this.$t(res.msg+''));
            }
        },
        handleError1(){
            this.spinShow = false;
            this.$Message.error(this.$t("600512") + "!");
        },
        delfile(){
            this.filename = '';
            this.fileurl = '';
        },
        /*********文件上传 end******** */
        handleRowChange(currentRow, oldCurrentRow) {
            this.detailobj = currentRow;
        },
        handlePageSize(value) {
            this.page = 1;
            this.pagesize = value;
            this.search(0);
        },
        changePage(value) {
            this.page = value;
            this.search(0);
        },
        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.tosearch();
            } else {
                if ((res.msg + "").indexOf(",") != -1) {
                    inittip(res.msg);
                } else {
                    this.$Message.error(this.$t(res.data));
                }
            }
        },
        handleError() {
            this.$Message.error(this.$t("2010006") + "!");
        },
    }
}
</script>
<style lang="less">
    .accountInfoUploadFile{
        display:inline-block;
        position: relative;
        left: 5px;
        .ivu-upload{
            display: inline-block;
            width: 140px;
            height: 29px;
            vertical-align: middle;
            .descicon{
                width: 140px;
                height:29px;
                line-height: 29px;
            }
        }
        .ivu-upload-drag{
            border:1px solid #dcdee2!important;
        }
        .ivu-upload-drag:hover {
            border: 1px solid #2d8cf0!important;
        }
        .hasfile{
            display: inline-block;
            position: relative;
            left: -140px;
            top: 29px;
            i{
                color: red;
                font-size: 15px;
                cursor: pointer;
                vertical-align: top;
            }
        }
    }
</style>