<template>
  <div>
    <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
         class="searchSelect"
        ></Cascader>
      </div>
      <div class="filter">
        <label>{{$t('5500024')}}：</label>
        <Select v-model="productid" clearable filterable class="searchSelect">
          <!--  -->
          <Option
            v-for="item in products"
            :value="item.id"
            :key="item.code"
          >{{ item.name }}[{{item.code}}]</Option>
        </Select>
      </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="dele()">{{$t('1004')}}</Button>
        <Button type="primary" class="fourWord" icon="md-download" @click="loadexcel()">{{$t('1005')}}</Button>
        <Upload
          style="display:inline-block"
          ref="upload"
          :action="action"
          name="excel-file"
          :headers="headers"
          :show-upload-list="false"
          :on-format-error="handleFormatError"
          :on-success="handleSuccess"
          :on-error="handleError"
          :format="['xlsx']"
        >
          <Button type="primary" class="fourWord" icon="md-cloud-upload">{{$t('1006')}}</Button>
        </Upload>
        <Button type="primary" class="fourWord" icon="ios-cloud-download" @click="Export()">{{$t('1007')}}</Button>
      </div>
    </div>
    <div class="divborder newTableDiv">
      <Table
        class="tableClass"
        @on-current-change="handleRowChange"
        @on-selection-change="selecttrchange"
        highlight-row
        :data="tableData"
        :columns="tableColumns"
      ></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="modeltitle" v-model="modal1" :styles="{width:'650px'}">
      <div class="filter">
        <label><i>*</i>{{$t(100395)}}：</label>
        <Select
          v-model="detailobj.line"
          @on-change="initstation(detailobj.line)"
          label-in-value
          clearable
          class="searchSelect"
        >
          <Option
            v-for="item in lines"
            :value="item.id"
            :key="item.id"
          >{{ item.id > 0 ? item.title :'' }}</Option>
        </Select>
      </div>
      <div class="filter">
        <label><i>*</i>{{$t(930064)}}：</label>
        <Select v-model="detailobj.section" label-in-value clearable class="searchSelect">
          <Option
            v-for="item in stations"
            :value="item.id"
            :key="item.id"
          >{{ item.id > 0 ? item.title :'' }}</Option>
        </Select>
      </div>
      <div class="filter">
        <label><i>*</i>{{$t('100307')}}：</label>
        <Select
          v-model="detailobj.productId"
          label-in-value
          @on-change="routechange"
          clearable
          class="searchSelect"
        >
          <Option
            v-for="item in products"
            :value="item.id"
            :key="item.id"
          >{{ item.id > 0 ? item.name+"【"+ item.code +"】" : '' }}</Option>
        </Select>
      </div>
      <div class="filter">
        <label><i>*</i>{{$t('920165')}}：</label>
        <Select v-model="detailobj.materialId" label-in-value clearable class="searchSelect">
          <Option
            v-for="item in materials"
            :value="item.id"
            :key="item.id"
          >{{ item.id > 0 ? item.name+"【"+ item.pn +"】" + "【" + item.spec + "】" : '' }}</Option>
        </Select>
      </div>

      <div class="filter">
        <label><i>*</i>{{$t('300084')}}：</label>
        <Input type="number" v-model="detailobj.count" class="searchInput" />
      </div>

      <div slot="footer">
        <Button type="text" size="large" @click="cancel">{{$t('1033')}}</Button>
        <Button type="primary" v-if="type===1" size="large" @click="saveAdd">{{$t('1002')}}</Button>
        <Button type="primary" v-if="type===2" size="large" @click="saveEdit">{{$t('1011')}}</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import axios from '@/libs/api.request';

export default {
    data () {
        return {
            action:
        axios.publicPath +
        'qms/upload/submit?templateName=Structure',
            headers: {
                token: localStorage.getItem('token'),
                timestamp: localStorage.getItem('timestamp'),
                nonce: localStorage.getItem('nonce'),
                sign: localStorage.getItem('sign')
            },
            modeltitle: '',
            productid: '', // 产品
            products: [],
            sectionid: [], // 通道层级
            datalevel: [],
            leveldata: [],
            lines: [],
            stations: [],
            total: 0,
            page: 1,
            pagesize: 10,
            detailobj: { id: 0, productId: 0, productCode: '', prodcutName: '', materialId: 0, materialName: '', line: 0, section: 0, count: 0 },
            tableRowObj: {},
            delelistobj: [], // 删除的所有对象
            tableData: [],
            tableColumns: [
                {
                    type: 'selection',
                    width: 50,
                    align: 'center'
                },
                {
                    type: 'index2',
                    title: this.$t('1008'),
                    key: 'xuhao',
                    render: (h, params) => {
                        return h(
                            'span',
                            params.index + (this.page - 1) * this.pagesize + 1
                        );
                    },
                    width: '70px'
                },
                {
                    title: this.$t('100395'),
                    key: 'sectionDesc'
                },
                {
                    title: this.$t('100089'),
                    key: 'productCode'
                },
                {
                    title: this.$t('100088'),
                    key: 'prodcutName'
                },
                {
                    title: this.$t('100390'),
                    key: 'pn'
                },
                {
                    title: this.$t('100391'),
                    key: 'materialName'
                },
                {
                    title: this.$t('100392'),
                    key: 'materialSpec'
                },
                {
                    title: this.$t('300084'),
                    key: 'count'
                }
            ],
            // 模态框数据
            modal1: false,
            productid1: '',
            materialid: '',
            materials: [],
            sectionid1: [],
            number: 0,
            type: 0
        };
    },
    created () {
        this.initproducts();
        this.initlevel();
        this.search(1, 10);
        // 格式化表格样式
        this.tableColumns = this.$time.initTableTitle(this.tableColumns)
    },
    methods: {
        initproducts () {
            // 获取产品
            axios
                .request({
                    url: '/config/projectproduct/GetProducts',
                    method: 'get'
                })
                .then(res => {
                    this.products = res.data.data;
                });
        },
        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;
                });
        },
        initmaterials (id) {
            // 根据产品获得物料
            this.materials = [{ id: 0, name: '', pn: '', spec: '' }];
            axios
                .request({
                    url: '/config/Material/GetSonMaterialsByProduct?productid=' + id,
                    method: 'get'
                })
                .then(res => {
                    this.materials = res.data.data;
                });
        },
        routechange () {
            // 监听产品变化
            this.initmaterials(this.detailobj.productId);
        },
        initline () {
            // 获取通道层级
            axios
                .request({
                    url: 'config/ProjectLevelSection/GetLine',
                    method: 'get'
                })
                .then(res => {
                    this.lines = res.data.data;
                });
        },
        initstation (line) {
            this.stations = [];

            axios
                .request({
                    url: 'config/ProjectLevelSection/GetStation?line=' + line,
                    method: 'get'
                })
                .then(res => {
                    this.stations = res.data.data;
                });
        },
        search (page, pagesize) {
            // 查询
            let selct = 0;
            if (this.sectionid.length > 0) {
                selct = this.sectionid[this.sectionid.length - 1];
            }
            var params = {
                section: selct,
                productId: this.productid,
                page: page,
                pagesize: pagesize
            };
            axios
                .request({
                    url: '/qms/ManufacturingMaterial/GetList',
                    params,
                    method: 'get'
                })
                .then(res => {
                    this.page = page;
                    this.pagesize = pagesize;
                    this.total = res.data.total;
                    this.mockTableData1(res.data.data);
                });
            this.detailobj = {};
            this.tableRowObj = {};
        },
        mockTableData1 (tablelist) {
            // 渲染表格
            let data = [];
            tablelist.forEach(item => {
                if (item) {
                    data.push({
                        product_name: item.product_name,
                        productCode: item.productCode,
                        productId: item.productId,
                        prodcutName: item.prodcutName,
                        materialId: item.materialId,
                        pn: item.pn,
                        materialName: item.materialName,
                        materialSpec: item.materialSpec,
                        line: item.line,
                        section: item.section,
                        sectionDesc: item.sectionDesc,
                        count: item.count,
                        id: item.id
                    });
                }
            });
            this.tableData = data;
        },
        selecttrchange (value) {
            this.delelistobj = value;
        },
        add () {
            this.detailobj = {};
            this.type = 1; // 添加
            this.initline();
            this.modal1 = true;
            this.modeltitle = this.$t('1002')
        },
        edit () {
            // 编辑
            this.detailobj = this.$time.deepClone(this.tableRowObj);
            if (this.detailobj.id == undefined || this.detailobj.id == 0) {
                this.$Message.error(this.$t('1014'));
                return;
            }
            this.initline();
            this.initstation(this.detailobj.line);
            this.routechange();
            this.type = 2; // 修改
            this.modal1 = true;
            this.modeltitle = this.$t('1003')
        },
        dele () {
            if (this.delelistobj.length < 1) {
                this.$Message.error(this.$t('1017'));
                return false;
            }
            this.confirm();
        },
        confirm () {
            // 确认删除
            this.$Modal.confirm({
                title: this.$t('600013'), // 提示
                content: '<p>' + this.$t('1018') + '</p>', // 确认删除吗？
                onOk: () => {
                    var arr = [];
                    this.delelistobj.forEach(item => {
                        arr.push(item.id);
                    });
                    var data = {
                        ids: arr
                    };
                    this.axios
                        .request({
                            url: '/qms/ManufacturingMaterial/Del',
                            data,
                            method: 'post'
                        })
                        .then(res => {
                            if (res.data.ret === 1) {
                                this.$Message.success(this.$t('1'));
                                this.search(1, this.pagesize);
                                this.delelistobj = [];
                            } else {
                                this.$Message.error(this.$t(res.data.msg));
                            }
                        });
                },
                onCancel: () => {
                    return false;
                }
            });
        },
        saveAdd () {
            // 保存

            if (this.detailobj.section == undefined || this.detailobj.section == 0) {
                this.$Message.error(this.$t('1950580'));
                return;
            }
            if (this.detailobj.productId == undefined || this.detailobj.productId == 0) {
                this.$Message.error(this.$t('100217'));
                return;
            }
            if (this.detailobj.materialId == undefined || this.detailobj.materialId == 0) {
                this.$Message.error(this.$t('1950603'));
                return;
            }
            if (this.detailobj.count == undefined || this.detailobj.count == 0) {
                this.$Message.error(this.$t('5500039'));
                return;
            }
            var data = {
                productId: this.detailobj.productId,
                materialId: this.detailobj.materialId,
                section: this.detailobj.section,
                count: this.detailobj.count
            };

            axios
                .request({
                    url: '/qms/ManufacturingMaterial/Add',
                    data,
                    method: 'post'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.$Message.success(this.$t('1055'));
                        this.search(this.page, this.pagesize);
                        this.modal1 = false;
                        this.detailobj = {};
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        saveEdit () {
            var data = {
                id: this.detailobj.id,
                productId: this.detailobj.productId,
                materialId: this.detailobj.materialId,
                section: this.detailobj.section,
                count: this.detailobj.count
            };
            axios
                .request({
                    url: '/qms/ManufacturingMaterial/Modify',
                    data,
                    method: 'post'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.$Message.success(this.$t('90000054'));
                        this.search(this.page, this.pagesize);
                        this.modal1 = false;
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        cancel () {
            this.modal1 = false;
        },
        loadexcel () {
            // 下载模板
            // 下载模板
            axios
                .request({
                    url: '/config/download/GetTemplate?name=Structure',
                    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));
                    }
                });
        },
        Export () {
            // 导出
            let selct = 0;
            if (this.sectionid.length > 0) {
                selct = this.sectionid[this.sectionid.length - 1];
            }
            let params = {
                section: selct,
                productId: this.productid
            }
            axios
                .request({
                    url: '/qms/ManufacturingMaterial/ExportExcel',
                    params,
                    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));
                    }
                });
        },
        /** 表格处理 */
        handleRowChange (currentRow, oldCurrentRow) {
            this.detailobj = currentRow;
            this.tableRowObj = this.$time.deepClone(currentRow);
        },
        handlePageSize (value) {
            this.pagesize = value;
            this.tableData1 = this.search(this.page, this.pagesize);
        },
        changePage (value) {
            this.page = value;
            this.tableData1 = this.search(this.page, this.pagesize);
        },
        handleFormatError (file) {
            this.$Message.error(this.$t('950396') + file.name + this.$t('950397'))
        },
        handleSuccess (res, file) {
            if (res.ret == 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('2010006') + '!');
        }
    }
};
</script>

<style>
</style>
