<template>
  <div class="testdiv">
    <div class="divborder newSearchDiv" style="margin:0px;">
      <div>
        <div class="filter">
          <label id="产品名称">{{$t('100088')}}：</label>
          <Select
            v-model="productId"
            @on-change="loadRoute(productId)"
            label-in-value
            clearable
             class="searchSelect"
          >
            <Option
              v-for="item in productlist"
              :value="item.id"
              :key="item.id"
            >{{item.code}}-{{ item.name }}</Option>
          </Select>
        </div>
        <div class="filter">
          <label id="物料编号">{{$t('100390')}}：</label>
          <Select v-model="materialId" label-in-value clearable  class="searchSelect">
            <Option
              v-for="item in materiallist"
              :value="item.id"
              :key="item.id"
            >{{item.pn}} {{ item.name }} {{item.spec}}</Option>
          </Select>
        </div>
        <div class="filter">
          <label id="返修工序">{{$t('100388')}}：</label>
          <Select v-model="preRoute" label-in-value clearable  class="searchSelect">
            <Option v-for="item in productRoutelist" :value="item.id" :key="item.id">{{ item.name }}</Option>
          </Select>
        </div>

            <div class="filter">
              <label id="返修后工序">{{$t('100389')}}：</label>
              <Select v-model="route" label-in-value clearable  class="searchSelect">
                <Option
                  v-for="item in productRoutelist"
                  :value="item.id"
                  :key="item.id"
                >{{ item.name }}</Option>
              </Select>
            </div>

      </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="asyncDelete()">{{$t('1004')}}</Button>
        <Button type="primary" class="fourWord" icon="md-download" @click="loadexcel()">{{$t('1005')}}</Button>
        <Upload
          style="display:inline-block"
          ref="upload"
          action="/qms/upload/submit?templateName=ReworkSetting"
          name="excel-file"
          :headers="headers"
          :show-upload-list="false"
          :on-format-error="handleFormatError"
          :on-success="handleSuccess"
          :on-error="handleError"
          :format="['xlsx']"
        >
          <Button type="primary" class="fourWord" icon="md-cloud-upload">{{$t('1006')}}</Button>
        </Upload>
        <Button type="primary" class="fourWord" icon="ios-cloud-download" @click="downexcel()">{{$t('1007')}}</Button>
      </div>

    </div>
    <Modal class="newModalClass" :title="$t(1002)" v-model="addmodal" :styles="{width:'700px'}">
      <div>
        <div class="filter">
          <label id="产品名称"><i>*</i>{{$t('100088')}}：</label>
          <Select
            v-model="addProductId"
            label-in-value
            @on-change="loadRouteAdd(addProductId)"
            clearable
            class="searchSelect"
          >
            <Option
              v-for="item in productlistAdd"
              :value="item.id"
              :key="item.id"
            >{{item.code}}-{{ item.name }}</Option>
          </Select>
        </div>
        <div class="filter">
          <label id="物料编号"><i>*</i>{{$t('100390')}}：</label>
          <Select
            v-model="addMaterialId"
            label-in-value
            clearable
           class="searchSelect"
          >
            <Option
              v-for="item in materiallistAdd"
              :value="item.id"
              :key="item.id"
            >{{item.pn}} {{ item.name }} {{item.spec}}</Option>
          </Select>
        </div>
      </div>
      <div>
        <div class="filter">
          <label id="返修工序">
           <i>*</i> {{$t('100388')}}：

          </label>
          <Select v-model="addPreRoute" label-in-value clearable class="searchSelect">
            <Option
              v-for="item in productRoutelistAdd"
              :value="item.id"
              :key="item.id"
            >{{ item.name }}</Option>
          </Select>
        </div>
        <div class="filter">
          <label id="返修工序到">
             <i>*</i>{{$t('100389')}}：

          </label>
          <Select v-model="addRoute" label-in-value clearable class="searchSelect">
            <Option
              v-for="item in productRoutelistAdd"
              :value="item.id"
              :key="item.id"
            >{{ item.name }}</Option>
          </Select>
        </div>
      </div>
      <div slot="footer">
        <Button type="text" size="large" @click="addmodal=false">{{$t(1033)}}</Button>
        <Button type="primary" size="large" @click="asyncAdd">{{$t(1011)}}</Button>
      </div>
    </Modal>
    <Modal class="newModalClass" :title="$t(900311)" v-model="editmodal" :loading="loading" :styles="{width:'700px'}">
      <div>
        <div class="filter">
          <label id="产品名称"><i>*</i>{{$t('100088')}}：</label>
          <Select
            v-model="detailobj.productId"
            label-in-value
            disabled
            @on-change="loadRouteEdit(detailobj.productId)"
            clearable
            class="searchSelect"
          >
            <Option
              v-for="item in productlistEdit"
              :value="item.id"
              :key="item.id"
            >{{item.code}}-{{ item.name }}</Option>
          </Select>
        </div>
        <div class="filter">
          <label id="物料编号"><i>*</i>{{$t('100390')}}：</label>
          <Select
            v-model="detailobj.materialId"
            label-in-value
            clearable
            class="searchSelect"
          >
            <Option
              v-for="item in materiallistEdit"
              :value="item.id"
              :key="item.id"
            >{{item.pn}} {{ item.name }} {{item.spec}}</Option>
          </Select>
        </div>
      </div>
      <div>
        <div class="filter">
          <label id="返修工序"><i>*</i>{{$t('100388')}}：</label>
          <Select v-model="detailobj.preRoute" label-in-value clearable class="searchSelect">
            <Option
              v-for="item in productRoutelistEdit"
              :value="item.id"
              :key="item.id"
            >{{ item.name }}</Option>
          </Select>
        </div>
        <div class="filter">
          <label id="返修工序到"><i>*</i>{{$t('100389')}}：</label>
          <Select
            v-model="detailobj.route"
            label-in-value
            clearable
            class="searchSelect"
          >
            <Option
              v-for="item in productRoutelistEdit"
              :value="item.id"
              :key="item.id"
            >{{ item.name }}</Option>
          </Select>
        </div>
      </div>
      <div slot="footer">
        <Button type="text" size="large" @click="editmodal=false">取消</Button>
        <Button type="primary" size="large" @click="asyncEdit">确定</Button>
      </div>
    </Modal>
    <div class="divborder newTableDiv">
      <Table
        class="tableClass"
        @on-current-change="handleRowChange"
        @on-selection-change="handleSelectRow"
        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>
  </div>
</template>
<script>
import axios from '@/libs/api.request'
export default {
    name: 'Businessmanagement', // 组件不刷新
    data () {
        return {
            headers: {
                token: localStorage.getItem('token'),
                timestamp: localStorage.getItem('timestamp'),
                nonce: localStorage.getItem('nonce'),
                sign: localStorage.getItem('sign')
            },
            morecondition: false,
            Sn: '',
            productId: 0,
            addProductId: 0,
            productlist: [],
            productlistAdd: [],
            productlistEdit: [],
            materialId: 0,
            addMaterialId: 0,
            materiallist: [],
            materiallistAdd: [],
            materiallistEdit: [],
            preRoute: 0,
            addPreRoute: 0,
            route: 0,
            addRoute: 0,
            productRoutelist: [],
            productRoutelistAdd: [],
            productRoutelistEdit: [],
            daterange: '',
            dtStart: '',
            dtEnd: '',
            tableData1: [],
            total: 0,
            page: 1,
            pagesize: 10,
            addmodal: false,
            loading: true,
            editmodal: false,
            addObj: {},
            detailobj: {},
            // 克隆对象
            tableRowObj: {},
            tableColumns1: [
                {
                    type: 'selection',
                    width: 50,
                    align: 'center'
                },
                {
                    type: 'index2',
                    title: this.$t(1008),
                    key: 'xuhao',
                    width: 70,
                    render: (h, params) => {
                        return h(
                            'span',
                            params.index + (this.page - 1) * this.pagesize + 1
                        )
                    }
                },

                {
                    title: this.$t(100089),
                    key: 'productcode'
                },
                {
                    title: this.$t('100088'),
                    key: 'productname'
                },
                {
                    title: this.$t('100390'),
                    key: 'pn'
                },
                {
                    title: this.$t('100391'),
                    key: 'materialName'
                },
                {
                    title: this.$t('100392'),
                    key: 'materialSpec'
                },
                {
                    title: this.$t('100388'),
                    key: 'preRouteDesc'
                },
                {
                    title: this.$t('100389'),
                    key: 'routeDesc'
                }
            ],
            selectids: []
        }
    },
    created () {
        this.InitTime()
        this.selectdate(this.daterange)
        this.loadProcduct()
        this.loadMaterial()
        this.search(1, 10)
        // 格式化表格样式
        this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1)
    },
    methods: {
        handleSelectRow: function (data) {
            this.selectids = []
            for (var i in data) {
                if (this.selectids.indexOf(data[i].id) < 0) {
                    this.selectids.push(data[i].id)
                }
            }
        },
        InitTime () {
            var nowtime = Date.parse(new Date()) / 1000
            var oldtime = nowtime - 86400 * 7
            this.daterange = [
                this.datetrans(oldtime) + '00:00:00',
                this.datetrans(nowtime) + '23:59:59'
            ]
        },
        datetrans (date) {
            if (date === '' || date === undefined || date === 0 || date === null) {
                return ''
            }
            date = new Date(date * 1000)
            var Y = date.getFullYear() + '-'
            var M =
        (date.getMonth() + 1 < 10
            ? '0' + (date.getMonth() + 1)
            : date.getMonth() + 1) + '-'
            var D =
        (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
            return Y + M + D
        },
        selectdate (e) {
            this.dtStart = e[0]
            this.dtEnd = e[1]
        },
        changecondition () {
            this.morecondition = !this.morecondition
        },
        timechange () {
            this.index_time = this.$time.changetime(this.datetype)
        },
        // 加载全部产品
        loadProcduct () {
            axios
                .request({
                    url: 'config/projectproduct/GetProducts',
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.productlist = res.data.data
                        this.productlistAdd = res.data.data
                        this.productlistEdit = res.data.data
                    } else {
                        this.$Message.error(this.$t(res.data.msg))
                    }
                })
        },
        // 加载全部物料
        loadMaterial () {
            axios
                .request({
                    url: 'config/Material/GetMaterialList',
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.materiallist = res.data.data
                        this.materiallistAdd = res.data.data
                        this.materiallistEdit = res.data.data
                    } else {
                        this.$Message.error(this.$t(res.data.msg))
                    }
                })
        },
        loadMaterialAdd (productId) {
            var params = {
                productId: productId
            }
            axios
                .request({
                    url: 'config/Material/GetMaterialByProcut',
                    params,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.materiallistAdd = res.data.data
                    } else {
                    }
                })
        },
        loadMaterialEdit (productId) {
            var params = {
                productId: productId
            }
            axios
                .request({
                    url: 'config/Material/GetMaterialByProcut',
                    params,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.materiallistEdit = res.data.data
                    } else {
                    }
                })
        },
        loadRoute (productId) {
            var params = {
                productId: productId
            }
            axios
                .request({
                    url: 'config/ProductRoute/GetRoutesByProduct',
                    params,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.productRoutelist = res.data.data
                    } else {
                        this.$Message.error(this.$t(res.data.msg))
                    }
                })
        },
        loadRouteAdd (productId) {
            this.loadMaterialAdd(productId)
            var params = {
                productId: productId
            }
            axios
                .request({
                    url: 'config/ProductRoute/GetRoutesByProduct',
                    params,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.productRoutelistAdd = res.data.data
                    } else {
                        this.$Message.error('未找到产品工序')
                    }
                })
        },
        loadRouteEdit (productId) {
            var params = {
                productId: productId
            }
            axios
                .request({
                    url: 'config/ProductRoute/GetRoutesByProduct',
                    params,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.productRoutelistEdit = res.data.data
                    } else {
                        this.$Message.error('未找到产品工序')
                    }
                })
        },
        search (page, pagesize) {
            var data = {
                page: page,
                pagesize: pagesize,
                productId: this.productId,
                materialId: this.materialId,
                route: this.route,
                preRoute: this.preRoute
            }
            axios
                .request({
                    url: '/qms/RepairSetting/Getlist',
                    data,
                    method: 'post'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.total = res.data.total
                        this.mockTableData1(res.data.data)
                        this.detailobj = {}
                        this.page = res.data.page
                    }
                })
        },
        mockTableData1 (tablelist) {
            let data = []
            tablelist.forEach(item => {
                if (item) {
                    data.push({
                        id: item.id,
                        productId: item.productId,
                        productcode: item.productCode,
                        productname: item.productName,
                        materialId: item.materialId,
                        pn: item.pn,
                        materialName: item.materialName,
                        materialSpec: item.materialSpec,
                        preRoute: item.preRoute,
                        preRouteDesc: item.preRouteDesc,
                        route: item.route,
                        routeDesc: item.routeDesc,
                        datetime: item.datetime
                    })
                }
            })
            this.tableData1 = data
        },
        add () {
            this.addmodal = true
        },
        asyncAdd () {
            if (this.addProductId === 0) {
                this.$Message.error('产品不能为空')
                return false
            }
            if (this.addMaterialId === 0) {
                this.$Message.error('物料不能为空')
                return false
            }
            if (this.addPreRoute === 0) {
                this.$Message.error('返回前工位不能空')
                return false
            }
            if (this.addRoute === 0) {
                this.$Message.error('返工工序')
                return false
            }
            if (this.addRoute === this.addPreRoute) {
                this.$Message.error('返工工序一致')
                return false
            }
            var data = {
                productId: this.addProductId,
                materialId: this.addMaterialId,
                preRoute: this.addPreRoute,
                route: this.addRoute
            }
            axios
                .request({
                    url: '/qms/RepairSetting/add',
                    data,
                    method: 'post'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.$Message.success(this.$t(1055))

                        this.addProductId = 0
                        this.addMaterialId = 0
                        this.addPreRoute = 0
                        this.addRoute = 0
                        setTimeout(() => {
                            this.addmodal = false
                        }, 500)
                        // this.addmodal = false
                        this.search(1, 10)
                    } else {
                        this.$Message.error(this.$t(res.data.msg))
                    }
                })
        },
        edit () {
            if (this.detailobj.id == null) {
                this.$Message.error(this.$t(90000081))
                return
            } else {
                this.detailobj = this.$time.deepClone(this.tableRowObj)
            }
            this.loadMaterialEdit(this.detailobj.productId)
            this.loadRouteEdit(this.detailobj.productId)
            this.editmodal = true
        },
        asyncEdit () {
            if (this.detailobj.preRoute === this.detailobj.route) {
                this.$Message.error('返工工序一致')
                return false
            }
            var data = {
                id: this.detailobj.id,
                productId: this.detailobj.productId,
                materialId: this.detailobj.materialId,
                preRoute: this.detailobj.preRoute,
                route: this.detailobj.route
            }
            axios
                .request({
                    url: '/qms/RepairSetting/Modify',
                    data,
                    method: 'post'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.$Message.success(this.$t(90000054))
                        this.search(1, 10)
                        this.editmodal = false
                    } else {
                        this.$Message.error(this.$t(res.data.msg))
                    }
                })
        },
        asyncDelete () {
            if (this.selectids === undefined || this.selectids === null || this.selectids === []) {
                this.$Message.error((this.$t('1017')))
                return false
            } else {
                this.$Modal.confirm({
                    title: this.$t('1018'),
                    content: '',
                    width: '290px',
                    closable: true,
                    okText: this.$t('1004'),
                    onOk: () => {
                        let parameter = {
                            ids: this.selectids
                        }
                        axios.request({
                            url: '/qms/RepairSetting/Delete',
                            data: parameter,
                            method: 'post'
                        }).then(res => {
                            if (res.data.ret === 1) {
                                this.page = 1
                                this.selectids = []
                                this.search(this.page, this.pagesize)
                                this.$Message.success(this.$t('1058'))
                            } else {
                                this.$Message.error(this.$t(res.data.msg))
                            }
                        })
                    }
                })
            }
        },
        loadexcel () {
            axios
                .request({
                    url: '/config/download/GetTemplate?name=ReworkSetting',
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        window.location.href = axios.publicPath + '' + res.data.data
                    } else {
                        this.$Message.error(this.$t(res.data.msg))
                    }
                })
        },
        downexcel () {
            var data = {
                productId: this.productId,
                materialId: this.materialId,
                route: this.route,
                preRoute: this.preRoute
            }
            axios
                .request({
                    url: '/qms/RepairSetting/ExporExcel',
                    data,
                    method: 'post'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        window.location.href = axios.publicPath + '' + res.data.data
                    } else {
                        this.$Message.error(this.$t(res.data.msg))
                    }
                })
        },
        handlePageSize (value) {
            this.pagesize = value
            this.search(this.page, this.pagesize)
        },
        changePage (value) {
            this.page = value
            this.search(this.page, this.pagesize)
        },
        handleRowChange (currentRow, oldCurrentRow) {
            this.detailobj = currentRow
            this.tableRowObj = this.$time.deepClone(currentRow)
        },
        handleFormatError (file) {
            this.$Message.error(this.$t('950396') + file.name + this.$t('950397'))
        },
        handleSuccess (res, file) {
            if (res.ret === 1) {
                this.page = 1
                this.search(this.page, this.pagesize)
                this.$Message.success(this.$t('950398'))
            } else {
                if ((res.msg + '').indexOf(',') != -1) {
                    inittip(res.msg)
                } else {
                    this.$Message.error(this.$t(res.msg))
                }
            }
        },
        handleError () {
            this.$Message.error(this.$t('950399'))
        }
    }
}
</script>
