<template>
    <div class="testdiv">
       <div class="divborder newSearchDiv">
           <div class="filter">
                <label>{{$t('300000')}}：</label>
                <Cascader :data="typelevel" :value="typeleveldata" @on-change="typechange" trigger="click" change-on-select class="searchSelect" ></Cascader>
            </div>
            <div class="filter">
                <label>{{$t('300087')}}：</label>
                <Input class="searchInput"  type="text"  v-model="mname"/>
          </div>
          <div class="searchBtn">
                <Button type="primary" class="twoWord" icon="ios-search" @click="search(1,pagesize)">{{$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="loaddemo()">{{$t('800049')}}</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 class="fourWord" icon="md-arrow-round-up" type="primary" >{{$t('1006')}}</Button>
                </Upload>
                <Button class="fourWord" icon="md-cloud-download" @click="loadexcel()" type="primary" >{{$t('1007')}}</Button>
            </div>
       </div>

       <div class="divborder newTableDiv">
          <Table
             class="tableClass"
            @on-current-change="handleRowChange"
            @on-selection-change="selecttrchange"
            border
            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" :title="$t('1002')" v-model="addmodal" :styles="{width:'650px'}" >
            <div class="modal_body">
                <Row style="height:100%;">
                    <Col span="10" style="height:400px;">
                      <Tree :data="treedata" @on-select-change="gettreeNodes" ref="tree" style="border:1px solid #eee;height:100%;border-radius:4px;overflow-y:scroll"></Tree>
                    </Col>
                    <Col span="12" style="height:100%;">
                        <div class="filter">
                            <label><i>*</i>{{$t(300087)}}：</label>
                            <Input class="searchInput" type="text"  v-model="addmname" />
                        </div>
                        <div class="filter">
                            <label>{{$t(950377)}}：</label>
                             <Select v-model="adduser" label-in-value clearable filterable class="searchSelect" >
                                <Option v-for="item in userlist" :value="item.mid" :key="item.mid">{{ item.name }}</Option>
                            </Select>
                        </div>
                        <div class="filter">
                            <label>{{$t(300052)}}：</label>
                            <Input class="searchInput" type="text"  v-model="addmdescribe" />
                        </div>
                    </Col>
                </Row>
            </div>
            <div slot="footer">
                <Button type="text" size="large" @click="addmodelcancel" v-text="$t('1033')">取消</Button>
                <Button type="primary" size="large" @click="adddata" v-text="$t('1011')">确定</Button>
            </div>
      </Modal>

      <Modal class="newModalClass" :title="$t('1003')" v-model="editmodal"   :styles="{width:'400px'}" >
            <div class="modal_body" >
                <Row style="height:100%;">
                    <Col span="24" style="height:100%;">
                        <div class="filter">
                            <label><i>*</i>{{$t(300087)}}：</label>
                            <Input class="searchInput" type="text"  v-model="obj.typename" />
                        </div>
                        <div class="filter">
                            <label>{{$t(950377)}}：</label>
                             <Select v-model="obj.userId" label-in-value filterable clearable class="searchSelect" >
                                <Option v-for="item in userlist" :value="item.mid" :key="item.mid">{{ item.name }}</Option>
                            </Select>
                        </div>
                        <div class="filter">
                            <label>{{$t(300052)}}：</label>
                            <Input class="searchInput" type="text"  v-model="obj.typedescribe" />
                        </div>
                    </Col>
                </Row>
            </div>
            <div slot="footer">
                <Button type="text" size="large" @click="editmodelcancel" v-text="$t('1033')">取消</Button>
                <Button type="primary" size="large" @click="editdata" v-text="$t('1011')">确定</Button>
            </div>
      </Modal>
    </div>
</template>
<script>
export default {
    data () {
        return {
            headers: { // 上传请求头添加
                token: localStorage.getItem('token'),
                timestamp: localStorage.getItem('timestamp'),
                nonce: localStorage.getItem('nonce'),
                sign: localStorage.getItem('sign')
            },
            typelevel: [], // 备件类型数据
            typeleveldata: [], // 备件类型value
            mname: '', // 备件类型名称
            total: 0, // 初始化数据总数
            page: 1, // 初始页码
            pagesize: 10, // 初始页码条数
            tableData1: [], // 表格数据
            addmodal: false, // 控制添加模态框出现与消失
            addmname: '', // 添加备件类型名称
            adduser: 0,
            addmdescribe: '', // 添加添加备件类型描述
            selectedtreenode: [], //
            editmodal: false,
            action: this.axios.publicPath + 'tpm/Upload/Submit?templateName=SparepartTypeList',
            obj: {},
            table_row_obj: {}, // 某一行选中的对象，用来应对修改优化
            delelistobj: [], // tr多选发生变化时的数组
            userlist: [],
            treedata: [
                {
                    title: this.$t('300000'), // 备件类型
                    expand: true,
                    id: 0,
                    children: []
                }
            ], // 树初始化数据
            tableColumns1: [ // 表头
                {
                    type: 'selection',
                    width: 60,
                    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: 65,
                    align: 'center'
                },
                {
                    title: this.$t('300088'), // 备件种类名称
                    key: 'typename',
                    align: 'center'
                },
                {
                    title: this.$t('300051'), // 上级备件类型
                    key: 'supertype',
                    align: 'center'
                },
                {
                    title: this.$t('300052'), // 备件类型描述
                    key: 'typedescribe',
                    align: 'center'
                },
                {
                    title: this.$t('300053'), // 包含备件种类数
                    key: 'typenumber',
                    align: 'center'

                }
            ]
        }
    },
    created () {
        this.inittype()
        this.search(1, 10)
        this.inittree()
        this.inituser()
        // 格式化表格样式
        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(1, 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('950399'))
        },
        // 备件类型变化
        typechange (value) {
            this.typeleveldata = value
        },
        // 初始化备件类型
        inittype () {
            this.axios.request({
                url: '/tpm/SparepartType/SparepartListType',
                method: 'get'
            }).then(res => {
                this.typelevel = res.data.data.children
            })
        },
        inituser () {
            this.axios.request({
                url: '/config/projectuser/GetAllUserByCurrentProjectId',
                method: 'get'
            }).then(res => {
                this.userlist = res.data.data
            })
        },
        search (page, pagesize) {
            var params = {
                id: this.typeleveldata.length === 0 ? 0 : this.typeleveldata[this.typeleveldata.length - 1],
                typename: this.mname,
                page: page,
                pagesize: pagesize
            }
            this.axios.request({
                url: '/tpm/SparepartType/GetSparepartTypeItem',
                params,
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1) {
                    this.total = res.data.total
                    this.mockTableData1(res.data.data)
                    this.page = res.data.page
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        },
        mockTableData1 (tablelist) {
            let data = []
            tablelist.forEach(item => {
                if (item) {
                    data.push({
                        typename: item.title,
                        supertype: item.pretitle,
                        typedescribe: item.description,
                        typenumber: item.total,
                        userId: item.userId,
                        id: item.id
                    })
                }
            })
            this.tableData1 = data
        },
        handleRowChange (currentRow, oldCurrentRow) { // 点击之后将某一行的数据添加到obj的对象中
            this.obj = currentRow
            this.table_row_obj = this.$time.deepClone(currentRow)
        },
        changePage (value) {
            this.page = value
            this.tableData1 = this.search(this.page, this.pagesize)
        },
        handlePageSize (value) { // 改变数据条数触发函数
            this.pagesize = value
            this.tableData1 = this.search(this.page, this.pagesize)
        },
        add () {
            this.inittree()
            this.addmname = ''
            this.adduser = 0
            this.addmdescribe = ''
            this.addmodal = true
        },
        // 获取tree组件的选中子节点
        gettreeNodes (value) {
            // console.log(value)
            this.selectedtreenode = value
        },
        adddata () {
            if (this.selectedtreenode === undefined || this.selectedtreenode === []) {
                this.$Message.error(this.$t('900692'))
                return false
            }
            if (this.selectedtreenode.length === 0) {
                this.$Message.error(this.$t('900692'))
                return false
            }
            if (this.addmname === '') {
                this.$Message.error(this.$t('9900026'))
                return false
            }
            var reg = new RegExp("[`~!@%#$^&*()=|{}':;',\\[\\]<>/?／＼］\\.；：%……+￥（）【】‘”“'．。，、？１２３４５６７８９０－＝＿＋～？！＠＃＄％＾＆＊）]")
            if (reg.test(this.addmname) || reg.test(this.description)) {
                this.$Message.error(this.$t('800064'))
                return false
            }
            var data = {
                title: this.addmname,
                userId: this.adduser,
                description: this.addmdescribe,
                parentid: this.selectedtreenode[0].id
            }
            this.axios.request({
                url: '/tpm/SparepartType/AddSparepartType',
                data,
                method: 'post'
            }).then(res => {
                if (res.data.ret === 1) {
                    this.$Message.success(this.$t('1055'))
                    this.search(1, this.pagesize)
                    this.addmodal = false
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        },
        addmodelcancel () {
            this.addmodal = false
        },
        inittree () {
            this.axios.request({
                url: '/tpm/SparepartType/SparepartListType',
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1) {
                    this.treedata[0].children = res.data.data.children
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        },
        edit () {
            if (this.obj.id === undefined) {
                this.$Message.error(this.$t('1017'))
                return false
            }
            this.editmname = ''
            this.editmdescribe = ''
            this.editmodal = true
            // this.inituser()
            this.obj = this.$time.deepClone(this.table_row_obj)
        },
        editmodelcancel () { // 编辑模态框取消
            this.editmodal = false
        },
        editdata () { // 编辑
            if (this.obj.typename === '') {
                this.$Message.error(this.$t('9900026'))
                return false
            }
            var reg = new RegExp("[`~!@%#$^&*()=|{}':;',\\[\\]<>/?／＼］\\.；：%……+￥（）【】‘”“'．。，、？１２３４５６７８９０－＝＿＋～？！＠＃＄％＾＆＊）]")
            if (reg.test(this.obj.typename) || reg.test(this.obj.typedescribe)) {
                this.$Message.error(this.$t('800064'))
                return false
            }
            var data = {
                title: this.obj.typename,
                userId: this.obj.userId,
                description: this.obj.typedescribe,
                id: this.obj.id
            }
            this.axios.request({
                url: '/tpm/SparepartType/EditSparepartType',
                data,
                method: 'post'
            }).then(res => {
                if (res.data.ret === 1) {
                    this.$Message.success(this.$t('1055'))
                    this.search(1, this.pagesize)
                    this.editmodal = false
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        },
        selecttrchange (value) {
            this.delelistobj = value
        },
        dele () {
            if (this.delelistobj.length < 1) {
                this.$Message.error(this.$t('1017'))
                return false
            }
            this.confirm()
        },
        loaddemo () {
            this.axios.request({
                url: '/config/download/GetTemplate?name=SparepartTypeList',
                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))
                }
            })
        },
        loadexcel () {
            var params = {
                id: this.typeleveldata.slice(-1),
                typename: this.mname
            }
            this.axios.request({
                url: '/tpm/SparepartType/ExportSparepartType',
                params,
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1) {
                    window.location.href = this.axios.publicPath + '' + res.data.data
                    // alert(this.$t('1'))
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        },

        confirm () { // 确认删除
            this.$Modal.confirm({
                title: this.$t('1018'),
                content: '',
                width: '290px',
                closable: true,
                okText: this.$t('1004'),
                onOk: () => {
                    var arr = []
                    this.delelistobj.forEach(item => {
                        arr.push(item.id)
                    })
                    var data = {
                        ids: arr
                    }
                    this.delelist = arr
                    this.axios.request({
                        url: '/tpm/SparepartType/DeleteScategorys',
                        data,
                        method: 'post'
                    }).then(res => {
                        if (res.data.ret === 1) {
                            this.search(1, this.pagesize)
                            this.$Message.success(this.$t('1'))
                        } else {
                            this.$Message.error(this.$t(res.data.msg))
                        }
                    })
                },
                onCancel: () => {
                    return false
                }
            })
        }
    }
}
</script>
<style lang="less" scoped>

</style>
