<template>
  <div class="testdiv">
    <div class="divborder newSearchDiv" style="margin:0px;">
        <div class="filter">
          <label>{{$t(100395)}}：</label>
          <Cascader
            :data="datalevel"
            :value="leveldata"
            v-model="sectionid"
            trigger="click"
            change-on-select
            @on-change="changeSection"
            class="searchSelect"
          ></Cascader>
        </div>
        <div class="filter">
          <label id="产品名称">{{$t('100088')}}：</label>
          <Select
            v-model="productId"
            label-in-value
            @on-change="loadMaterialByProduct(productId)"
            clearable
           class="searchSelect"
          >
            <Option
              v-for="item in productlist"
              :value="item.productId"
              :key="item.productId"
            >{{ item.productName }}</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('800008')}}：</label>
            <Input class="searchInput" type="text" id="input1" v-model="sn" />
          </div>
      <!-- 次级搜索条件--隐藏 -->
      <div v-show="!morecondition">
        <div>

          <div class="filter">
            <label>{{$t('1035')}}</label>
            <DatePicker
              id="日期"
              type="datetimerange"
              v-model="daterange"
              confirm
              placeholder=""
              class="searchInput MaxWidth"
              format="yyyy-MM-dd HH:mm:ss"
              @on-change="selectdate"
            ></DatePicker>
          </div>
        </div>
      </div>
      <div class="searchBtn">
        <Button type="primary" class="twoWord" icon="ios-search" @click="search()">{{$t('1001')}}</Button>
        <!-- <Button type="success" 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="asynDel()">{{$t('1004')}}</Button>
        <Button type="primary" class="fourWord" icon="ios-cloud-download" @click="downexcel()">{{$t('1007')}}</Button>
      </div>

      <!-- 更多条件 按钮 -->
      <MoreConbtn @getCon="morecondition = !morecondition" :morecondition="morecondition"></MoreConbtn>
    </div>
    <Modal class="newModalClass" :title="$t(930051)" v-model="editmodal" :styles="{width:'720px'}">
      <div class="modal_body" style="padding:0 20px;">
        <div>
          <div class="filter">
            <label id="二维码">{{$t('800008')}}：</label>
            <Input type="text" v-model="detailobj.sn" class="searchInput MaxWidth" />
          </div>

          <div class="filter">
            <label id="产线">
              <i>*</i>{{$t('1950574')}}：</label>
            <Select
              v-model="detailobj.sectionParent"
              @on-change="chanelChanged(detailobj.sectionParent)"
              label-in-value
              clearable
              class="searchSelect"
            >
              <Option
                v-for="item in this.chanellst"
                :value="item.id"
                :key="item.id"
              >{{ item.title }}</Option>
            </Select>
          </div>
          <div class="filter">
            <label id="返工工位">
              <i>*</i>{{$t('100388')}}：
            </label>
            <Select
              v-model="detailobj.settingId"
              @on-change="dropDown"
              label-in-value
              clearable
              class="searchSelect"
            >
              <Option
                v-for="item in this.chanelStaion"
                :value="item.settingId"
                :key="item.settingId"
                :tag="item.id"
              >{{ item.item }}</Option>
            </Select>
          </div>

          <div class="filter">
            <label id="产品名称">
              <i>*</i>{{$t('100088')}}：
            </label>
            <Select
              v-model="detailobj.productid"
              @on-change="loadMaterialByProductAdd(detailobj.productid)"
              label-in-value
              clearable
              class="searchSelect"
            >
              <Option
                v-for="item in this.productlistAdd"
                :value="item.productId"
                :key="item.productId"
              >{{ item.productName }}</Option>
            </Select>
          </div>
          <div class="filter">
            <div class="filter">
              <label id="物料编号">{{$t('100390')}}：
              </label>
              <Select
                v-model="detailobj.materailId"
                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 class="filter">
            <label id="数量">{{$t('300084')}}：</label>
            <Input type="number" v-model="detailobj.count" class="searchInput" />
          </div>
             <div class="filter">
            <label id="报废备注">{{$t('600648')}}：</label>
            <Select
              v-model="detailobj.referType"
              label-in-value
              clearable
              filterable
              allow-create
              @on-change="loadRefer(detailobj.referType)"
              class="searchSelect"
            >
              <Option
                v-for="item in this.referencetype"
                :value="item.id"
                :key="item.id"
              >{{ item.name }}</Option>
            </Select>
          </div>
          <div class="filter">
            <label id="报废备注">
              {{$t('900289')}}：
            </label>
            <Select
              v-model="detailobj.remark"
              label-in-value
              clearable
              filterable
              allow-create
              class="searchSelect"
            >
              <Option
                v-for="item in this.reference"
                :value="item.remark"
                :key="item.remark"
              >{{ item.remark }}</Option>
            </Select>
          </div>

          <div>
            <label id="项目" class="item">{{$t('901048')}}：</label>
            <div style="display:inline-block" class="tests">
              <RadioGroup
                v-model="detailobj.oItemId"
                style="width:500px;vertical-align:top;padding-left:20px;"
                vertical
              >
                <Radio
                  v-for="item in this.oqcItemlist"
                  :label="item.id"
                  :key="item.id"
                  style="margin-left:0px;text-align: start;"
                >
                  <Icon type="social-apple"></Icon>
                  <span>{{item.item}}</span>
                </Radio>
              </RadioGroup>
            </div>
          </div>
        </div>
      </div>
      <div></div>
      <div slot="footer">
        <Button type="text" size="large" @click="cancle()">{{$t(1033)}}</Button>
        <Button type="primary" size="large" @click="asyncSave()">{{$t(1011)}}</Button>
      </div>
    </Modal>
    <div class="divborder newTableDiv">
      <Table
       class="tableClass"
        @on-current-change="handleRowChange"
        highlight-row
        :data="tableData1"
        :columns="tableColumns1"
      ></Table>
      <div class="pageDiv">
        <div class="pageDirection">
          <Page
            :total="total"
            :current="page"
            @on-change="changePage"
            show-elevator
            show-sizer
            show-total
            @on-page-size-change="handlePageSize"
            :page-size-opts="[10,20,30,40,100]"
          ></Page>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import axios from '@/libs/api.request';
import moment from 'moment';

export default {
    name: 'Businessmanagement', // 组件不刷新
    data () {
        return {
            morecondition: false,
            count: 1,
            sn: '',
            addSn: '',
            addRadio: 1,
            productId: 0,
            productIdAdd: 0,
            materialId: 0,
            materialIdAdd: 0,
            productlist: [],
            productlistAdd: [],
            materiallist: [],
            materiallistAdd: [],
            oqcItemlist: [],
            addSntype: 1,
            addPreRoute: 0,
            addRoute: 0,
            addItem: 0,
            addRemark: '',
            preRoute: 0,
            route: 0,
            preRouteAdd: 0,
            routeAdd: 0,
            productRoutelist: [],
            productRoutelistAdd: [],
            productPositionRework: [],
            daterange: '',
            dtStart: '',
            dtEnd: '',
            tableData1: [],
            total: 0,
            page: 1,
            pagesize: 10,
            editmodal: false,
            addObj: {},
            detailobj: {},
            // 克隆对象
            tableRowObj: {},
            scanObj: {},
            leveldata: [],
            datalevel: [],
            sectionid: [],
            position: 0,
            reference: [],
            tongdao: 0,
            tongdaolist: [],
            staion: 0,
            stationlist: [],
            chanellst: [],
            chanelStaion: [],
            tableColumns1: [
                {
                    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(800008),
                    key: 'sn',
                    width: 200
                },
                {
                    title: this.$t(100089),
                    key: 'productcode',
                    width: 150
                },
                {
                    title: this.$t(100088),
                    key: 'productname',
                    width: 150
                },
                {
                    title: this.$t(100390),
                    key: 'pn',
                    width: 150
                },
                {
                    title: this.$t(100391),
                    key: 'materialName',
                    width: 150
                },
                {
                    title: this.$t(100392),
                    key: 'materialSpec',
                    width: 120
                },
                // {
                //   title: "工站",
                //   key: "section"
                // },
                {
                    title: this.$t(100388),
                    key: 'section',
                    width: 230
                },
                {
                    title: this.$t(950224),
                    key: 'routeDesc',
                    width: 230
                },
                {
                    title: this.$t(90000042),
                    key: 'oItem',
                    width: 120
                },
                // {
                //   title: "返工类型",
                //   key: "typeDesc"
                // },
                {
                    title: this.$t(300084),
                    key: 'count',
                    width: 100
                },
                {
                    title: this.$t(90000043),
                    key: 'datetime',
                    width: 160
                },
                {
                    title: this.$t(950228),
                    key: 'remark',
                    width: 230
                },
                {
                    title: this.$t(950412),
                    key: 'user',
                    width: 120
                }
            ],
            referencetype: [], // 类型
            reference: []
        };
    },
    created () {
        this.InitTime();
        this.initlevel();
        this.loadChanel();
        this.selectdate(this.daterange);
        this.search();
        // 格式化表格样式
        this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1)
    },
    methods: {
        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'
            ];
        },
        initlevel () {
            // 获取通道层级
            axios
                .request({
                    url: 'config/ProjectLevelSection/GetSectionTree',
                    method: 'get'
                })
                .then(res => {
                    const arr = [];
                    this.datalevel = res.data.data;
                    arr.push(res.data.data[0].value);
                    this.leveldata = arr;
                });
        },
        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];
            let last_str = this.dtEnd.split(' ')[1];
            if (last_str === '00:00:00') {
                this.dtEnd = moment(this.dtEnd).format('YYYY-MM-DD') + ' 23:59:59';
                this.daterange = [this.dtStart, this.dtEnd];
            }
        },
        changecondition () {
            this.morecondition = !this.morecondition;
        },
        timechange () {
            this.index_time = this.$time.changetime(this.datetype);
        },
        loadMaterialByProduct (productId) {
            var params = {
                productId: productId
            };
            axios
                .request({
                    url: 'config/Material/GetMaterialByProcut',
                    params,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.materiallist = res.data.data;
                    } else {
                    }
                });
        },
        loadMaterialByProductAdd (productId) {
            if (productId === 0) {
                return;
            }
            this.materialIdAdd = 0;
            this.materiallistAdd = [];
            this.oqcItemlist = [];
            this.loadOQCItem(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 {
                    }
                });
        },
        loadReferType () {
            axios
                .request({
                    url: '/qms/ReworkReferenceType/GetItem?type=1',
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.referencetype = res.data.data;
                    } else {
                        // this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },

        loadRefer (type) {
            axios
                .request({
                    url: '/qms/ReworkReference/GetItem?type=1&referType=' + type, // "/qms/ReworkReferenceType/GetItem?type=2",
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.reference = res.data.data;
                    } else {
                        // this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        changeSection () {
            let selct = 0;
            if (this.sectionid.length > 0) {
                selct = this.sectionid[this.sectionid.length - 1];
            }
            if (selct == 0) {
                return;
            }
            this.loadloadProductBySection(selct);
        },
        chanelChanged (id) {
            axios
                .request({
                    url: '/qms/RepairPostionSetting/GetSettingByChanel?Id=' + id,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.chanelStaion = res.data.data;
                        this.loadloadProductBySection(id);
                    } else {
                        // this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        loadChanel () {
            axios
                .request({
                    url: '/qms/RepairPostionSetting/GetChanel',
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.chanellst = res.data.data;
                    } else {
                        // this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        loadStation () {
            axios
                .request({
                    url: '/config/ProjectLevelSection/GetStation?line=' + this.tongdao,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.stationlist = res.data.data;
                    } else {
                        // this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        // 位置选择带出产品
        loadloadProductBySection (id) {
            this.productlistAdd = [];
            this.productlist = [];
            var params = {
                sectionId: id
            };
            axios
                .request({
                    url: '/qms/InspectStandard/GetOQCItemProduct',
                    params,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.productlistAdd = res.data.data;
                        this.productlist = res.data.data;
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        cancle () {
            this.editmodal = false;
        },
        dropDown (val) {
            if (val === undefined) {
                return false;
            }

            this.detailobj.sectionId = val.tag;
            this.loadOQCItem(this.detailobj.productid);
        },
        // 产品带出检验项
        loadOQCItem (productId) {
            var params = {
                productid: productId,
                sectionid: this.detailobj.sectionId
            };
            axios
                .request({
                    url: '/qms/InspectStandard/GetItems',
                    params,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.oqcItemlist = res.data.data;
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        handleCreate (val) {
            if (this.reference.length > 0) {
                var obj = this.reference[this.reference.length - 1];
                var step = 1;
                if (obj != null) {
                    step = obj.id + 1;
                }

                this.reference.push({
                    remark: val,
                    id: step
                });
            } else {
                this.reference.push({
                    remark: val,
                    id: 1
                });
            }
        },

        search () {
            let selct = 0;
            if (this.sectionid.length > 0) {
                selct = this.sectionid[this.sectionid.length - 1];
            }
            var data = {
                page: this.page,
                pagesize: this.pagesize,
                productId: this.productId,
                MaterialId: this.materialId,
                Section: selct, // this.tongdao,
                Route: this.staion,
                PreRoute: this.preRoute,
                Sn: this.sn,
                beginTime: this.dtStart,
                endTime: this.dtEnd,
                reworkDataType: 1
            };
            axios
                .request({
                    url: '/qms/RepairData/Getlist',
                    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) {
            let data = [];
            tablelist.forEach(item => {
                if (item) {
                    data.push({
                        id: item.id,
                        productid: item.productId,
                        productcode: item.productCode,
                        productname: item.productName,
                        pn: item.pn,
                        materailId: item.materailId,
                        materialName: item.materialName,
                        materialSpec: item.materialSpec,
                        section: item.section,
                        sectionParent: item.sectionParentId, // 返工通道
                        sectionId: item.sectionId, // 返工工站
                        sn: item.sn,
                        type: item.type,
                        typeDesc: item.typeDesc,
                        preRoute: item.preRoute,
                        preRouteDesc: item.preRouteDesc,
                        route: item.route, // 返工到
                        routeDesc: item.routeDesc,
                        datetime: item.datetime,
                        refer: item.refer,
                        referType: item.referType,
                        remark: item.remark,
                        user: item.user,
                        count: item.count,
                        oItem: item.oItem,
                        oItemId: item.oItemId,
                        settingId: item.settingId // 返工设置ID
                    });
                }
            });
            this.tableData1 = data;
        },
        edit () {
            if (this.detailobj === null || this.detailobj.id === undefined) {
                this.$Message.error(this.$t('1014'));
                return;
            }
            this.detailobj = this.$time.deepClone(this.tableRowObj);
            this.loadChanel();
            this.loadReferType();
            this.loadRefer(this.detailobj.referType);
            this.chanelChanged(this.detailobj.sectionParent);
            this.loadMaterialByProductAdd(this.detailobj.productid);
            this.loadOQCItem(this.detailobj.productid);
            this.editmodal = true;
        },
        asynDel () {
            if (this.detailobj.id === undefined || this.detailobj.id === 0) {
                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: () => {
                        axios
                            .request({
                                url: '/qms/RepairData/DelRecord?id=' + this.detailobj.id,
                                // data: parameter,
                                method: 'get'
                            })
                            .then(res => {
                                if (res.data.ret === 1) {
                                    this.page = 1;
                                    this.selectids = [];
                                    this.search();
                                    this.$Message.success(this.$t('1058'));
                                } else {
                                    this.$Message.error(this.$t(res.data.msg));
                                }
                            });
                    }
                });
            }
        },
        asyncSave () {
            if (this.detailobj.id === undefined || this.detailobj.id === 0) {
                this.$Message.error(this.$t(930049));
                return false;
            }
            if (
                this.detailobj.settingId === undefined ||
        this.detailobj.settingId === 0
            ) {
                this.$Message.error(this.$t(930050));
                return false;
            }
            if (
                this.detailobj.productid === undefined ||
        this.detailobj.productid === 0
            ) {
                this.$Message.error(this.$t(100217));
                return false;
            }
            // if (this.detailobj.materailId === undefined||this.detailobj.materailId === 0) {
            //   this.$Message.error(this.$t(1950603))
            //   return false
            // }
            var data = {
                Id: this.detailobj.id,
                Sn: this.detailobj.sn,
                ProductId: this.detailobj.productid,
                Materail: this.detailobj.materailId,
                SectionId: this.detailobj.route,
                SnType: this.detailobj.SnType,
                QID: this.detailobj.oItemId,
                Remark: this.detailobj.remark,
                Count: this.detailobj.count,
                SettingId: this.detailobj.settingId
            };
            axios
                .request({
                    url: '/qms/RepairData/ModifyRepair',
                    data,
                    method: 'post'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.page = 1
                        this.pagesize = 10
                        this.search();
                        this.$Message.success(this.$t(1060));
                        this.editmodal = false;
                        this.detailobj = {};
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        scan () {
            this.productIdAdd = 0;
            this.materialIdAdd = 0;
            var params = {
                sn: this.addSn
            };
            axios
                .request({
                    url: '/qms/RepairData/GetProductRoute',
                    params,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.productlistAdd = res.data.data;
                        if (this.productlistAdd.length > 0) {
                            this.productIdAdd = this.productlistAdd[0].productId;
                        }
                    } else {
                        this.addSn = '';
                    }
                });
        },

        handlePageSize (value) {
            this.pagesize = value;
            this.tableData1 = this.search();
        },
        changePage (value) {
            this.page = value;
            this.tableData1 = this.search();
        },
        handleRowChange (currentRow, oldCurrentRow) {
            this.detailobj = currentRow;
            this.tableRowObj = this.$time.deepClone(currentRow);
        },
        downexcel () {
            let selct = 0;
            if (this.sectionid.length > 0) {
                selct = this.sectionid[this.sectionid.length - 1];
            }
            var data = {
                productId: this.productId,
                materialId: this.materialId,
                route: this.staion,
                Section: selct,
                preRoute: this.preRoute,
                Sn: this.sn,
                beginTime: this.dtStart,
                endTime: this.dtEnd,
                reworkDataType: 1
            };
            axios
                .request({
                    url: '/qms/RepairData/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));
                    }
                });
        }
    }
};
</script>
<style lang="less" scoped>
.item {
  display: inline-block;
  height: 40px;
  font-size: 12px;
  margin-right: 15px;
  margin-top: 0px;
  width: 100px;
  text-align: end;
}
</style>
