<template>
  <div>
    <div class="divborder newSearchDiv"  style="margin:0px;">
      <div class="filter">
        <label>{{$t(100074)}}：</label>
        <Cascader :data="datamt" :value="mtdata" @on-change="machineTypeChange" trigger="hover" class="searchSelect"></Cascader>
      </div>
      <div class="filter">
        <label>{{$t(900750)}}：</label>
        <Select v-model="filterObj.wordType" label-in-value clearable class="searchSelect">
          <Option v-for="(item,key) in grouplist" :value="item.id" :key="key">{{item.title}}</Option>
        </Select>
      </div>
      <div class="filter">
        <label>{{$t(900752)}}：</label>
        <Input type="text" class="searchInput" placeholder=""  v-model="filterObj.wordName" />
      </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="warning" class="twoWord" icon="ios-create-outline" @click="edit()">{{$t('1003')}}</Button>
        <Button type="error" class="twoWord intervalRight" icon="md-close-circle" @click="del()">{{$t('1004')}}</Button>
        <Button type="primary" class="sixWord" icon="ios-create-outline" @click="editwordbtn()">{{$t('8000053')}}</Button>
      </div>
    </div>

    <div class="divborder newTableDiv">
      <Table class="tableClass" width='100%' @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" :title="modalTitle" v-model="addModal" @on-ok="handleSubmit('addObj')" :loading="loading" :styles="{width:'720px'}">
      <div class="modal_body">
        <Form ref="addObj" :model="addObj" label-position="top" :rules="addModalRule">
          <Row type="flex" justify="space-between" class="code-row-bg">
            <Col :span="10" v-if="optType==='add'" style="max-height:400px;overflow-y: auto;overflow-x: auto;">
            <template>
              <Tree ref="tree" :data="treeContents" :render="renderContent" expand="true"></Tree>
            </template>
            </Col>
            <Col :span="14" style="max-height:400px;overflow-y: auto;overflow-x: hidden;padding-left: 20px;">

            <FormItem :label="$t(99100042)" prop="word" class="clear wordaddmodal">
              <FileUpload :uList="addObj.word" :key="'word'" @activeName="outFileUploadChild($event)" v-model="addObj.word"></FileUpload>
            </FormItem>

            <FormItem :label="$t(900773)+'：'" prop="wordType" class="wordaddmodal">

              <Select v-model="addObj.wordType" class="searchSelect">
                <Option v-for="(item,key) in grouplist" :value="item.id" :key="key">{{item.title}}</Option>
                <!-- <Option v-for="(value,key) in initPageData.wordTypeList" :value="key" :key="key">{{value}}</Option> -->
              </Select>
            </FormItem>
            <FormItem :label="$t(1030)+'：'" prop="des" class="wordaddmodal">
              <Input
              type="textarea"
              v-model="addObj.des"
              class="searchInput MaxWidth"
              :autosize="{minRows: 3,maxRows: 3}"
            />
            </FormItem>
            </Col>
          </Row>
        </Form>
      </div>
    </Modal>
    <!-- 编辑文档类型 -->
    <Modal class="newModalClass" :title="editmodaltitle" v-model="editwordmodel"  :styles="{width:'600px'}">
      <div class="modal_body">
        <div class="filter">
          <label>{{$t(900752)}}：</label>
          <Input v-model="word_title" class="searchInput MaxWidth" />
        </div>
        <div>
          <div class="searchBtn" style="padding-left:80px;">
            <Button type="primary" class="twoWord" icon="ios-search" @click="searchword">{{$t('1001')}}</Button>
            <Button type="success" class="twoWord" icon="md-add-circle" @click="addword('')">{{$t('1002')}}</Button>
            <Button type="warning" class="twoWord" icon="ios-create-outline" @click="addword(1)">{{$t('1003')}}</Button>
            <Button type="error" class="twoWord" icon="md-close-circle" @click="delword">{{$t('1004')}}</Button>
          </div>
        </div>
        <div style="height:300px;overflow-y:scroll">
           <CheckboxGroup v-model="checklist">
              <Checkbox :label="item.id" v-for="(item,key) in grouplist" :key="key" style="">
                  <span>{{item.title}}</span>
              </Checkbox>
          </CheckboxGroup>
        </div>
      </div>
      <div slot="footer">
        <Button type="primary" size="large" @click="closeeditwordmodel" >确定</Button>
      </div>
    </Modal>
    <Modal class="newModalClass" :title="editmodaltitle" v-model="editworddetail"  :styles="{width:'600px'}">
      <div class="modal_body">
        <div class="filter">
          <label>{{$t(900752)}}:</label>
          <Input v-model.trim="editcheckObj.title"  class="searchInput MaxWidth" />
        </div>
      </div>
      <div slot="footer">
        <Button  size="large" @click="editworddetail=false" >取消</Button>
        <Button type="primary" size="large" @click="worddata" >确认</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import axios from '@/libs/api.request'
import FileUpload from '_c/file-upload/machine-file-upload.vue'
import { setTimeout } from 'timers';
export default {
    name: 'config-machine-word',
    components: {
        FileUpload
    },
    // data ************************************************************************************
    data () {
        const validateWord = (rule, value, callback) => { // 正整数
            if (value.length > 0) {
                callback()
            } else {
                return callback(new Error(this.$t(100400)))
            }
        }
        const validateWordType = (rule, value, callback) => { // 正整数
            if (/^[1-9]\d*$/.test(value)) {
                callback()
            } else {
                return callback(new Error(this.$t(100401)))
            }
        }
        return {
            editmodaltitle: this.$t('8000053'),
            datamt: [], // 插件所需数据
            mtdata: [], // 选中数据
            mtid: 0, //
            filterObj: {
                PMachineType: 0, // 父设备类型
                CMachineType: 0, // 子设备类型
                wordType: 0, // 文档类型
                wordName: '', // 文档名称
                uploadTime: [] // 上传时间
            },
            editwordmodel: false,
            word_title: '',
            grouplist: [], // checkbox列表
            checklist: [], // 多选框value
            editcheckObj: {},
            editworddetail: false, // 详情模态框
            initPageData: {
                wordTypeList: {
                    1: this.$t(900760),
                    2: this.$t(900761),
                    3: this.$t(900762),
                    4: this.$t(900763),
                    5: this.$t(900764),
                    6: this.$t(100402),
                    7: this.$t(600233)
                },
                projectList: []
            },
            treeContents: [],
            map: {
                value: 'machineid',
                label: 'name',
                children: 'children',
                expand: true,
                selected: false
            },
            addModal: false, // 添加Modal的开关
            loading: true,
            modalTitle: '',
            optType: 'add', // add,edit
            addObj: {
                id: 0,
                word: [],
                wordName: '',
                wordUrl: '',
                wordType: 0, // 文档类型
                des: '', // 备注
                machineid: 0 // 关联设备
            },
            selectedObj: {}, // 选中对象容器

            total: 0, // 刀位列表total
            page: 1, // 刀位列表当前页数
            pagesize: 10, // 刀位列表pagesize

            tableData1: [], // 刀位列表数据容器
            tableColumns1: [{ // 列表字段属性集合
                type: 'index2',
                title: this.$t(1008),
                key: 'xuhao',
                render: (h, params) => {
                    return h('span', params.index + (this.page - 1) * this.pagesize + 1)
                },
                width: 80
            },
            {
                title: this.$t(900774),
                key: 'machineName'
            },
            {
                title: this.$t(900752),
                key: 'wordTitle',
                render: (h, params) => {
                    return h('A', {
                        props: {
                            // target: '_blank'
                        },
                        on: {
                            'click': () => {
                                this.downWord(params)
                            }
                        }
                    }, params.row.wordTitle)
                }
            },
            {
                title: this.$t(900754),
                key: 'wordTypename'
            },
            {
                title: this.$t(900755),
                key: 'uploader'
            },
            {
                title: this.$t(900753),
                key: 'uploadTime'
            },
            {
                title: this.$t(1030),
                key: 'des'
            }
            ],
            headers: {
                token: localStorage.getItem('token'),
                timestamp: localStorage.getItem('timestamp'),
                nonce: localStorage.getItem('nonce'),
                sign: localStorage.getItem('sign')
            },
            addModalRule: {
                word: [{
                    required: true,
                    validator: validateWord,
                    trigger: 'blur'
                }],
                wordType: [{
                    required: true,
                    validator: validateWordType,
                    trigger: 'blur'
                }]
            }

        } // end return data
    },
    // created ************************************************************************************
    created () {
        this.defaultPageData()
        this.search(1, 10) // 初始化列表
        this.searchword('')
        // 格式化表格样式
        this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1)
    // this.initAddModal()
    },
    // methods ************************************************************************************
    methods: {
        closeeditwordmodel () {
            this.editwordmodel = false;
            this.search(1, this.pagesize)
        },
        defaultPageData () {
            this.inittree()
            this.initMT()
        },
        initMT () {
            axios.request({
                url: '/config/MachineType/GetMachineTypeTree',
                method: 'get'
            }).then(res => {
                this.datamt = res.data.data
                this.mtdata = []
            })
        },
        inittree () {
            axios.request({
                url: '/config/ProjectLevelSection/GetLevelSectionTreeForTpm',
                method: 'get'
            }).then(res => {
                this.treeContents = this.convertTree(res.data.data.children, this.map)
            })
        },
        // 树形数据转换
        convertTree (tree, map) {
            const result = []
            if (tree != undefined) {
                tree.forEach((item) => {
                    const value = item[map.value]
                    const label = item[map.label]
                    let children = item[map.children]
                    const expand = true
                    if (children) {
                        children = this.convertTree(children, map)
                    }
                    result.push({
                        value,
                        label,
                        children,
                        expand
                    })
                })
            }
            return result
        },
        renderContent (h, {
            root,
            node,
            data
        }) {
            return h('span', {
                style: {
                    display: 'inline-block',
                    width: '90%',
                    cursor: 'pointer'
                },
                class: node.node.selected ? 'treeSelect' : '',
                on: {
                    click: (e) => {
                        this.addObj.machineid = node.node.value
                        // console.log(this.addObj.machineid)
                        // console.log(node)
                    }
                }
            }, [
                h('span', [
                    h('span', data.label)
                ]),
                h('span', {
                    style: {
                        display: 'inline-block',
                        float: 'right',
                        marginRight: '10px'
                    }
                })
            ])
        },
        changePage (value) { // 换页事件
            this.page = value
            this.tableData1 = this.search(this.page, this.pagesize)
        },
        handleRowChange (currentRow, oldCurrentRow) { // 选中一条数据，触发事件
            this.selectedObj = currentRow
        },
        handlePageSize (value) { // 切换分页页数，触发事件
            this.pagesize = value
            this.tableData1 = this.search(this.page, this.pagesize)
        },
        search (page, pagesize) { // 点击查询，触发事件
            var data = {
                doc_name: this.filterObj.wordName, // 文档名称
                doc_time: '', // 上传时间
                doc_type: this.filterObj.wordType, // 文档类型
                machinetype1: this.filterObj.machinetype1, // 父设备类型
                machinetype2: this.filterObj.machinetype2, // 子设备类型
                page: page,
                pagesize: pagesize,
                section_id: 0 // 关联设备
            }
            axios.request({
                url: '/config/document/getMachineDocInfo',
                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,
                        machineName: item.machine_name,
                        wordTitle: item.doc_name,
                        wordTypename: item.doc_type_name,
                        wordType: item.doc_type,
                        uploader: item.user_name,
                        uploadTime: item.time,
                        des: item.remark,
                        url: item.url
                    })
                }
            })
            this.tableData1 = data
        },
        //* *****************************************************************************************
        outFileUploadChild (files) { // 接受文件上传的数据
            if (files.length < 1) {
                return false
            }
            this.addObj.word = files
            if (files != null && files.length > 0) {
                this.addObj.wordName = files[0].name
                this.addObj.wordUrl = files[0].response.data
            }
        },
        initAddModal () {
            this.$refs.addObj.resetFields()
        },
        add () { // 添加
            this.addModal = true
            this.modalTitle = '添加'
            this.optType = 'add'
            this.initAddModal() // 初始化
        },
        edit () {
            if (this.selectedObj.id === '' || this.selectedObj.id === undefined) {
                this.$Message.error(this.$t('1043'))
                return false
            }
            this.addModal = true
            this.modalTitle = this.$t(1003)
            this.optType = 'edit'
            this.initEditModal()
            // this.$refs.addObj.resetFields()
        },
        initEditModal () {
            let params = {
                id: this.selectedObj.id
            }
            axios.request({
                url: '/config/document/getMachineDocForEdit',
                params,
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1) {
                    let item = res.data.data
                    let files = item.doc_name != '' ? [{
                        name: item.doc_name,
                        url: axios.publicPath + item.url,
                        status: 'finished'
                    }] : []
                    this.addObj.id = item.id
                    this.addObj.word = files
                    this.addObj.des = item.remark
                    this.addObj.machineid = item.machine_id
                    this.addObj.wordType = item.doc_type
                    this.addObj.wordName = item.doc_name
                    this.addObj.wordUrl = item.url
                }
            })
        },
        del () { // 删除
            if (this.selectedObj.id === '' || this.selectedObj.id === undefined) {
                this.$Message.error((this.$t('1043')))
                return false
            } else {
                this.$Modal.confirm({
                    title: this.$t('1018'),
                    content: '',
                    width: '290px',
                    closable: true,
                    okText: this.$t('1004'),
                    onOk: () => {
                        axios.request({
                            url: '/config/document/DelMachineDoc?id=' + this.selectedObj.id,
                            method: 'post'
                        }).then(res => {
                            if (res.data.ret === 1) {
                                this.$Message.success(this.$t('1058'))
                                this.search(1, this.pagesize)
                            } else {
                                this.$Message.error(this.$t(res.data.msg))
                            }
                        })
                    }
                })
            }
        },
        down () { // 导出excel
            if (this.selectedObj.id === '' || this.selectedObj.id === undefined) {
                this.$Message.error((this.$t('1043')))
                return false
            } else {
                window.location = axios.publicPath + this.selectedObj.url
            }
        },
        downWord (params) { // 导出excel
            window.open(axios.publicPath + params.row.url)
        },

        handleSubmit (name) { // 添加
            this.$refs[name].validate((valid) => {
                if (valid) { // valid
                    let data
                    if (this.optType === 'add') { // 添加操作
                        if (this.addObj.machineid === 0) {
                            this.$Message.error(this.$t(100150))
                            this.clearLoading()
                            return false
                        }
                        // if (this.addObj.wordType === 0) {
                        //   this.$Message.error('请选择文档类型')
                        //   this.clearLoading()
                        //   return false
                        // }
                        // if (this.addObj.word.length === 0) {
                        //   this.$Message.error('请选择文档')
                        //   this.clearLoading()
                        //   return false
                        // }
                        data = {
                            title: this.addObj.wordName,
                            url: this.addObj.wordUrl,
                            sel_machine: 1,
                            sectionid: this.addObj.machineid,
                            type: this.addObj.wordType,
                            remark: this.addObj.des
                        }
                        axios.request({
                            url: '/config/document/addMachineDocment',
                            data,
                            method: 'post'
                        }).then(res => {
                            if (res.data.ret === 1) { // res.data.ret === 1
                                this.$Message.success(this.$t(1055))
                                this.addModal = false
                                this.search(1, 10)
                            } else {
                                this.$Message.error(this.$t(1056))
                                // 解决ok按钮loading的问题
                                this.clearLoading()
                            }
                        })
                    } else { // 修改
                        // if (this.addObj.machineid === 0) {
                        //   this.$Message.error('请选择设备')
                        //   this.clearLoading()
                        //   return false
                        // }
                        // if (this.addObj.wordType === 0) {
                        //   this.$Message.error('请选择文档类型')
                        //   this.clearLoading()
                        //   return false
                        // }
                        // if (this.addObj.word.length === 0) {
                        //   this.$Message.error('请选择文档')
                        //   this.clearLoading()
                        //   return false
                        // }
                        data = {
                            id: this.addObj.id,
                            title: this.addObj.wordName,
                            url: this.addObj.wordUrl,
                            sel_machine: 1,
                            sectionid: this.addObj.machineid,
                            type: this.addObj.wordType,
                            remark: this.addObj.des
                        }
                        axios.request({
                            url: '/config/document/EditMachineDoc',
                            data,
                            method: 'post'
                        }).then(res => {
                            if (res.data.ret === 1) { // res.data.ret === 1
                                this.$Message.success(this.$t(1060))
                                this.addModal = false
                                this.search(1, 10)
                            } else {
                                this.$Message.error(this.$t(1061))
                                // 解决ok按钮loading的问题
                                this.clearLoading()
                            }
                        })
                    }
                } else {
                    // 解决ok按钮loading的问题
                    this.clearLoading()
                }
            })
        },
        machineTypeChange (data) {
            this.filterObj.machinetype1 = data.length > 0 ? data[0] : 0
            this.filterObj.machinetype2 = data.length > 1 ? data[1] : 0
            // console.log(this.filterObj)
        },
        changeDate (dateA) {
            var dateee = new Date(dateA).toJSON()
            var date = new Date(+new Date(dateee) + 8 * 3600 * 1000).toLocaleDateString().replace(/T/g, ' ').replace(
                /\.[\d]{3}Z/,
                '').replace(/\//g, '-')
            return date
        },
        clearLoading () {
            this.loading = false
            this.$nextTick(() => {
                this.loading = true
            })
        },
        editwordbtn () {
            this.editwordmodel = true
            this.searchword()
        },
        searchword () {
            var params = {
                title: this.word_title ? this.word_title : ''
            }
            this.axios.request({
                url: 'config/Document/GetMachineDocTypes',
                params,
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1) {
                    this.grouplist = res.data.data
                } else {
                    this.$Message.error(this.$t('' + res.data.msg))
                }
            })
        },
        addword (index) {
            if (!index) {
                this.editcheckObj.id = 0
                this.editworddetail = true
            } else {
                if (this.checklist.length !== 1) {
                    this.$Message.error('请选择一项进行修改')
                    this.checklist = []
                    return false;
                } else {
                    this.grouplist.forEach(item => {
                        if (this.checklist[0] === item.id) {
                            this.editcheckObj = item
                        }
                    })
                    this.editworddetail = true
                }
            }
        },
        worddata () {
            var data = this.editcheckObj
            this.axios.request({
                url: '/config/Document/SetMachineDocType',
                data,
                method: 'post'
            }).then((res) => {
                if (res.data.ret === 1) {
                    this.$Message.success('操作成功')
                    this.editcheckObj = {}
                    this.checklist = []
                    this.searchword()
                    this.editworddetail = false
                } else {
                    this.$Message.error(this.$t('' + res.data.msg))
                }
            })
        },
        delword () {
            if (this.checklist.length < 1) {
                this.$Message.error('请先选择要删除的数据')
                return false
            }
            var params = {
                ids: this.checklist.join(',')
            }
            this.$Modal.confirm({
                title: this.$t('1018'),
                content: '',
                width: '290px',
                closable: true,
                okText: this.$t('1004'),
                onOk: () => {
                    axios.request({
                        url: 'config/Document/DelMachineDocType',
                        params,
                        method: 'get'
                    }).then(res => {
                        if (res.data.ret === 1) {
                            this.$Message.success(this.$t('1058'))
                            this.editcheckObj = {}
                            this.checklist = []
                            this.searchword()
                        } else {
                            setTimeout(() => { this.$Message.error(this.$t('' + res.data.msg)) }, 500)
                        }
                    })
                }
            })
        }
    }
}
</script>
<style lang="less">
  .treeSelect {
    span {
      background: #2D8CF1;
      color: #fff;
      margin: 0;
      padding: 0 4px;
      border-radius: 3px;
      cursor: pointer;
      vertical-align: top;
    }
  }
  .wordaddmodal{
    label{
      width: 100%!important;
      text-align: left!important;
    }
  }
</style>
