<template>
  <div>
    <div class="divborder newSearchDiv">
      <div class="filter">
        <label>{{$t(1132)}}：</label>
        <Cascader :data="datalevel" v-model="leveldata" trigger="click" change-on-select class="searchSelect"></Cascader>
      </div>
      <div class="filter">
        <label>{{$t(800191)}}：</label>
        <Select v-model="filterObj.typeMode" label-in-value clearable class="searchSelect">
          <Option v-for="(value,key) in initPageData.defendTypeList" :value="key" :key="key">{{value}}</Option>
        </Select>
      </div>
      <div class="filter">
        <label>{{$t(950330)}}：</label>
        <Select v-if="filterObj.typeMode==='1'" v-model="filterObj.import" label-in-value clearable class="searchSelect">
          <Option v-for="(value,key) in initPageData.levelList" :value="key" :key="key">{{value}}</Option>
        </Select>
        <Select v-else-if="filterObj.typeMode==='2'" v-model="filterObj.import" label-in-value clearable class="searchSelect">
          <Option v-for="(value,key) in initPageData.levelList2" :value="key" :key="key">{{value}}</Option>
        </Select>
        <Select v-else v-model="filterObj.import" label-in-value clearable class="searchSelect">
          <Option v-for="(value,key) in initPageData.levelList3" :value="key" :key="key">{{value}}</Option>
        </Select>
      </div>
      <div class="filter">
        <label>{{$t(1115)}}：</label>
        <Select v-model="filterObj.valueType" label-in-value clearable class="searchSelect">
          <Option value="1" key="1">{{$t(1118)}}</Option>
          <Option value="2" key="2">{{$t(1119)}}</Option>
        </Select>
      </div>

      <!-- 次级搜索条件--隐藏 -->
      <div v-show="!morecondition">
        <div>
          <div class="filter">
        <label>{{$t(1117)}}：</label>
        <Select v-model="filterObj.instructionCycle" label-in-value clearable class="searchSelect">
          <Option v-for="(value,key) in initPageData.instructionCycleList" :value="key" :key="key">{{value}}</Option>
        </Select>
      </div>
      <div class="filter">
        <label>{{$t(200063)}}：</label>
        <Select v-model="filterObj.compare" label-in-value clearable class="searchSelect" style="margin-right:10px;">
              <Option value="2" :key="2">{{$t(200026)}}</Option>
              <Option value="1" :key="1">{{$t(200027)}}</Option>
            </Select>
        <InputNumber  class="searchInput" v-model="filterObj.gt" :min="1"></InputNumber>
      </div>
      <div class="filter">
        <label>{{$t(200154)}}：</label>
        <Select v-model="filterObj.dateRang" label-in-value clearable class="searchSelect">
          <Option v-for="(value,key) in initPageData.dateRangList" :value="key" :key="key">{{value}}</Option>
        </Select>
      </div>
      <div class="filter">
        <label>{{$t(100000)}}：</label>
        <Select v-model="filterObj.department" @on-change="changeDepartment($event,'filter')" label-in-value clearable
          class="searchSelect">
          <Option v-for="item in initPageData.departmentList" :value="item.id" :key="item.id">{{item.title}}</Option>
        </Select>
      </div>
      </div>
      <div>
        <div class="filter">
        <label>{{$t(100046)}}：</label>
        <Select v-model="filterObj.user" label-in-value clearable class="searchSelect">
          <Option v-for="item in initPageData.userList" :value="item.id" :key="item.id">{{item.name}}</Option>
        </Select>
      </div>

       <div class="filter">
        <label>{{$t(200072)}}：</label>
        <DatePicker
          type="daterange"
          @on-change="timechange"
          :value="filterObj.startTime"
          placement="bottom-end"
          split-panels
          placeholder=""
           class="searchInput middleWidth"
        ></DatePicker>
      </div>
      </div>

      </div>
      <div class="searchBtn">
        <Button type="primary" class="twoWord" icon="ios-search"  @click="search(1,pagesize)">{{$t('1001')}}</Button>
        <Button type="warning" class="twoWord" icon="ios-create-outline" @click="edit()">{{$t(1003)}}</Button>
        <Button type="error" class="twoWord" icon="md-close-circle"  @click="del()">{{$t(1004)}}</Button>
        <!-- <Button type="primary" icon="ios-create-outline" @click="showDate()">日历</Button> -->
        <!-- <br />
        <div class="datePicker" :style="{height:filterObj.height+'px'}">
          <DatePicker @on-change="changeDatePicker" type="date" v-model="filterObj.time" format="yyyy-MM-dd" placement="bottom-start"
            split-panels :open="filterObj.open" placeholder="Select date" style="margin-top: -36px;position: absolute;left: 2px;"></DatePicker>
        </div> -->

      </div>
       <!-- 更多条件 按钮 -->
      <MoreConbtn @getCon="morecondition = !morecondition" :morecondition="morecondition"></MoreConbtn>
    </div>

    <div class="divborder newTableDiv">
      <Table  class="tableClass" width='100%' @on-selection-change="multipleSelection" @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="$t(200206)" v-model="changeModel"
      :styles="{width:'600px'}">
      <div class="modal_body arrangeModal" style="height: 120px !important;">

        <Form ref="changeExecutorObj" :model="changeExecutorObj" label-position="top">
          <div class="filter">
          <FormItem :label="$t(900745)" class="fl ml10 clear">
            <DatePicker type="date" v-model="changeExecutorObj.instruction_time" format="yyyy-MM-dd" placement="top-start"
              split-panels class="searchInput"></DatePicker>
          </FormItem>
          </div>
          <div class="filter">
          <FormItem  :label="$t(200207)" class="fl ml10 clear">
            <Select v-model="changeExecutorObj.department" :transfer="transferx" @on-change="changeDepartment($event,'changeExecutor')"
              label-in-value clearable class="searchSelect">
              <Option v-for="item in initPageData.departmentList" :value="item.id" :key="item.id">{{item.title}}</Option>
            </Select>
          </FormItem>
          </div>
          <div class="filter">
          <FormItem :label="$t(200208)" class="fl ml10 clear">
            <Select v-model="changeExecutorObj.user" :transfer="transferx" class="searchSelect">
              <Option v-for="item in changeExecutorObj.userList" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
          </FormItem>
          </div>
        </Form>
      </div>
      <div slot="footer">
        <Button type="text" size="large" @click="changeModel=false" v-text="$t('1033')">取消</Button>
        <Button type="primary" size="large" @click="handlerChangeExecutor('changeExecutorObj')" v-text="$t('1011')">确定</Button>
      </div>
    </Modal>

  </div>
</template>
<script>
import axios from '@/libs/api.request'
export default {
    name: 'tpm-defend-arrange',
    components: {

    },
    // data ************************************************************************************
    data () {
        return {
            transferx: true, // 优化下拉框
            leveldata: [], // 产线层级插件所需数据
            datalevel: [], // 产线层级选中数据
            levelid: 0, // 产线层级选中的section_id
            morecondition: false,
            filterObj: {
                typeMode: 0,
                valueType: 0,
                import: 0,
                instructionCycle: 0,
                dateRang: 0,
                department: 0,
                user: 0,
                lt: 0,
                gt: 0,
                open: false,
                time: '',
                height: 0,
                machineidarr: [],
                startTime: []
            },

            initPageData: {
                departmentList: [],
                userList: [],
                levelList: {
                    1: this.$t(950331),
                    2: this.$t(950332),
                    3: this.$t(950333),
                    4: this.$t(950334),
                    5: this.$t(950335),
                    6: this.$t(950336)
                },
                levelList2: {
                    10: this.$t(930077),
                    11: this.$t(800074),
                    12: this.$t(930078),
                    13: this.$t(930079)
                },
                levelList3: {
                    10: this.$t(930077),
                    11: this.$t(800074),
                    12: this.$t(930078),
                    13: this.$t(930079),
                    14: this.$t(930129)
                },
                levelListAll: {
                    1: this.$t(950331),
                    2: this.$t(950332),
                    3: this.$t(950333),
                    4: this.$t(950334),
                    5: this.$t(950335),
                    6: this.$t(950336),
                    10: this.$t(930077),
                    11: this.$t(800074),
                    12: this.$t(930078),
                    13: this.$t(930079)
                },
                defendTypeList: {
                    1: 'AM',
                    2: 'PM',
                    3: 'CMP'
                },
                defendTypeList2: {
                    1: 'AM',
                    2: 'PM',
                    3: 'CMP'
                },
                instructionCycleList: {
                    1: this.$t(1101),
                    7: this.$t(1136),
                    14: this.$t(1137),
                    30: this.$t(1138),
                    60: this.$t(1139),
                    90: this.$t(1140),
                    180: this.$t(1141),
                    365: this.$t(1142)
                },
                dateRangList: {
                    1: this.$t(200151),
                    2: this.$t(200152),
                    3: this.$t(200153)
                }

            },

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

            multipleSelectedObj: [],
            changeModel: false,
            loading: false,
            changeExecutorObj: {
                department: 0,
                userList: [],
                user: 0,
                instruction_time: '',
                selectedPlanTimeIds: []
            },
            tableData1: [], // 刀位列表数据容器
            tableColumns1: [
                {
                    title: '全选',
                    width: 60,
                    type: 'selection'
                },
                { // 列表字段属性集合
                    type: 'index2',
                    title: this.$t(1008),
                    key: 'xuhao',
                    render: (h, params) => {
                        return h('span', params.index + (this.page - 1) * this.pagesize + 1)
                    },
                    width: 100
                },
                {
                    title: this.$t(200003),
                    key: 'station'
                },
                {
                    title: this.$t(900337),
                    key: 'work_order'
                },
                {
                    title: this.$t(800191),
                    key: 'mode',
                    width: 90
                },
                {
                    title: this.$t(200058),
                    key: 'content'
                },
                {
                    title: this.$t(950330),
                    key: 'severity_level',
                    width: 100
                },
                {
                    title: this.$t(200063),
                    key: 'standard_time',
                    width: 160
                },
                {
                    title: this.$t(200072),
                    key: 'instruction_time_str'
                },
                {
                    title: this.$t(200073),
                    key: 'name',
                    width: 120
                }
            ]

        }
    },
    // created ************************************************************************************
    created () {
        this.defaultPageData()
        this.search(1, 10) // 初始化列表
        // 格式化表格样式
        this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1)
    },
    // methods ************************************************************************************
    methods: {
        timechange (value) {
            this.filterObj.startTime = value
        },
        defaultPageData () {
            this.initlevel() // 初始化产线层级
            this.initDepartmentList()
        },
        initDepartmentList () {
            axios.request({
                url: '/config/ProjectSection/GetSections',
                method: 'get'
            }).then(res => {
                if (res.data.data != undefined && res.data.data.length > 0) {
                    this.initPageData.departmentList = res.data.data
                } else {
                    this.initPageData.departmentList = []
                }
            })
        },
        changeDepartment (item, opt) {
            if (item === undefined) {
                return false
            }
            if (parseInt(item.value) > 0) {
                let params = {
                    sectionid: item.value
                }
                axios.request({
                    url: '/config/ProjectUser/getUserListsBySectionId',
                    params,
                    method: 'get'
                }).then(res => {
                    if (res.data.data != undefined && res.data.data.length > 0) {
                        if (opt === 'changeExecutor') {
                            this.changeExecutorObj.userList = res.data.data
                        } else {
                            this.initPageData.userList = res.data.data
                        }
                    } else {
                        if (opt === 'changeExecutor') {
                            this.changeExecutorObj.userList = []
                        } else {
                            this.initPageData.userList = []
                        }
                    }
                })
            }
        },
        initlevel () { // 初始化产线层级
            axios.request({
                url: 'config/ProjectLevelSection/GetSectionTree',
                method: 'get'
            }).then(res => {
                this.datalevel = res.data.data
                this.leveldata = []
            })
        },

        changePage (value) { // 换页事件
            this.page = value
            this.search(this.page, this.pagesize)
        },
        handleRowChange (currentRow, oldCurrentRow) { // 选中一条数据，触发事件
            this.selectedObj = currentRow
        },
        multipleSelection (multipleSelected) {
            this.multipleSelectedObj = multipleSelected
            if (this.multipleSelectedObj.length > 0) {
                let ptimeid = []
                this.multipleSelectedObj.forEach(item => {
                    ptimeid.push(item.id)
                })
                this.changeExecutorObj.selectedPlanTimeIds = ptimeid
            }
        },
        handlePageSize (value) { // 切换分页页数，触发事件
            this.pagesize = value
            this.search(this.page, this.pagesize)
        },
        search (page, pagesize) { // 点击查询，触发事件
            // if (this.leveldata === undefined || this.leveldata.length === 0) {
            //   this.$Message.error('请选择产线')
            //   return false
            // }
            var sectionid = (this.leveldata != undefined && this.leveldata.length > 0) ? this.leveldata[this.leveldata.length - 1] : 0
            axios.request({
                url: '/config/UserLevel/ListMachineIdArrEx?id=' + sectionid,
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1 && res.data.data.length > 0) {
                    this.filterObj.machineidarr = res.data.data
                    var data = {
                        value_type: this.filterObj.valueType,
                        severity_level: this.filterObj.import,
                        instruction_cycle: this.filterObj.instructionCycle,
                        person: this.filterObj.user,
                        mode: this.filterObj.typeMode, //
                        date_rang: this.filterObj.dateRang, //
                        machineidarr: this.filterObj.machineidarr,
                        compare: this.filterObj.compare,
                        gt: this.filterObj.gt,
                        stime: this.filterObj.startTime[0],
                        etime: this.filterObj.startTime[1],
                        page: page,
                        pagesize: pagesize
                    }
                    axios.request({
                        url: '/tpm/Plan/GetlistthirdPlanItem',
                        data,
                        method: 'POST'
                    }).then(res => {
                        if (res.data.ret === 1) {
                            this.total = res.data.total
                            this.mockTableData1(res.data.data)
                            this.page = res.data.page
                        }
                    })
                }
            })
        },
        mockTableData1 (tablelist) { // 转换数据，并赋值给列表数据容器tableData1
            let data = []
            tablelist.forEach(item => {
                if (item) {
                    data.push({
                        id: item.id,
                        station: item.station,
                        mode: item.mode === 1 ? 'AM' : (item.mode === 2 ? 'PM' : 'CMP'),
                        content: item.content,
                        severity_level: this.initPageData.levelListAll[item.severity_level],
                        standard_time: item.standard_time,
                        instruction_time_str: item.instruction_time_str,
                        name: item.name,
                        department: item.department,
                        mid: item.mid,
                        work_order: item.work_order // 工单号
                    })
                }
            })
            this.tableData1 = data
        },
        edit () {
            if (this.multipleSelectedObj.length === 0 || this.multipleSelectedObj === undefined) {
                this.$Message.error(this.$t(1043))
                return false
            }
            this.changeModel = true
            this.initEditModal()
            // this.$refs.changeExecutorObj.resetFields()
        },
        initEditModal () {
            if (this.multipleSelectedObj.length == 1) {
                this.changeExecutorObj.department = this.multipleSelectedObj[0].department
                this.changeExecutorObj.instruction_time = this.multipleSelectedObj[0].instruction_time_str
                this.changeExecutorObj.user = this.multipleSelectedObj[0].mid
                axios.request({
                    url: '/config/ProjectUser/getUserListsBySectionId?sectionid=' + this.multipleSelectedObj[0].department,
                    method: 'get'
                }).then(res => {
                    if (res.data.data != undefined && res.data.data.length > 0) {
                        this.changeExecutorObj.userList = res.data.data
                    } else {
                        this.changeExecutorObj.userList = []
                    }
                })
            } else {
                this.changeExecutorObj.department = 0
                this.changeExecutorObj.instruction_time = ''
                this.changeExecutorObj.user = 0
                this.changeExecutorObj.userList = []
            }
        },
        handlerChangeExecutor () {
            let data
            if (!this.changeExecutorObj.instruction_time || !this.changeExecutorObj.instruction_time) {
                this.$Message.error(this.$t(930080))
                // this.clearLoading()
                return false
            }

            // if (this.changeExecutorObj.department === 0) {
            //   this.$Message.error(this.$t(100239))
            //   this.clearLoading()
            //   return false
            // }
            // if (this.changeExecutorObj.user === 0 || this.changeExecutorObj.user === undefined) {
            //   this.$Message.error('请选择执行人')
            //   this.clearLoading()
            //   return false
            // }
            data = {
                instruction_time: this.changeDate(this.changeExecutorObj.instruction_time),
                instruction_mid: this.changeExecutorObj.user,
                ptimeid: this.changeExecutorObj.selectedPlanTimeIds
            }
            // console.log(data)
            // return false
            axios.request({
                url: '/tpm/Plan/EditPlansTime',
                data,
                method: 'post'
            }).then(res => {
                if (res.data.ret === 1) { // res.data.ret === 1
                    this.$Message.success(this.$t(1060))
                    this.search(this.page, this.pagesize)
                    // this.clearLoading()
                    this.changeModel = false
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                    this.changeModel = true
                    // 解决ok按钮loading的问题
                }
            })
        },
        del () {
            if (this.multipleSelectedObj.length === 0) {
                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: () => {
                        let data = {
                            planid: this.changeExecutorObj.selectedPlanTimeIds
                        }
                        axios.request({
                            url: '/tpm/Plan/DeletePlantimes',
                            data,
                            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))
                            }
                        })
                    }
                })
            }
        },
        showDate () {
            this.filterObj.open = !this.filterObj.open
            this.filterObj.height = this.filterObj.open ? 250 : 0
        },
        changeDatePicker (time) {
            var sectionid = (this.leveldata != undefined && this.leveldata.length > 0) ? this.leveldata[this.leveldata.length - 1] : 0
            axios.request({
                url: '/config/UserLevel/ListMachineIdArrEx?id=' + sectionid,
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1 && res.data.data.length > 0) {
                    this.filterObj.machineidarr = res.data.data
                    var data = {
                        value_type: this.filterObj.valueType,
                        severity_level: this.filterObj.import,
                        instruction_cycle: this.filterObj.instructionCycle,
                        timenum: time,
                        person: this.filterObj.user,
                        mode: this.filterObj.typeMode, //
                        date_rang: this.filterObj.dateRang, //
                        machineidarr: this.filterObj.machineidarr,
                        lt: this.filterObj.lt,
                        gt: this.filterObj.gt,
                        page: this.page,
                        pagesize: this.pagesize
                    }
                    axios.request({
                        url: '/tpm/Plan/GetlistPlanItem',
                        data,
                        method: 'POST'
                    }).then(res => {
                        if (res.data.ret === 1) {
                            this.total = res.data.total
                            this.mockTableData2(res.data.data)
                        }
                    })
                }
            })
        },
        mockTableData2 (tablelist) { // 转换数据，并赋值给列表数据容器tableData1
            let data = []
            tablelist.forEach(item => {
                if (item) {
                    data.push({
                        id: item.id,
                        station: item.station,
                        mode: this.initPageData.defendTypeList2[item.mode],
                        content: item.content,
                        severity_level: this.initPageData.levelList2[item.severity_level],
                        standard_time: item.standard_time,
                        instruction_time_str: item.instruction_time_str,
                        name: item.name,
                        department: item.department,
                        mid: item.mid
                    })
                }
            })
            this.tableData1 = data
        },
        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
            })
        },
        changecondition () {
            this.morecondition = !this.morecondition
        }

    }, // end methods
    watch: {

    }
}
</script>
<style lang="less">
  .datePicker {
    width: 222px;
    max-height: 250px;
    overflow: hidden;
    margin-top: 10px;
    position: relative;
    margin-left: 8px;
  }
  .arrangeModal{
    label{
      text-align: left!important;
    }
  }
</style>
