<template>
  <div class="testdiv">
    <!-- 查询条件 -->
    <div class="divborder newSearchDiv" style="margin:0px;">
      <div class="filter">
        <label>{{$t('900921')}}</label>
        <Input class="searchInput" type="text" v-model="productname" />
      </div>
      <div class="filter">
        <label>{{$t('900940')}}</label>
        <Input class="searchInput" type="text" v-model="productdrawno" />
      </div>
      <div class="filter">
        <label>{{$t('900939')}}</label>
        <Input class="searchInput" type="text" v-model="orderno" />
      </div>
      <div class="filter">
        <label>{{$t('99200041')}}：</label>
        <Input class="searchInput" type="text" v-model="produceno" />
      </div>
      <!-- 次级搜索条件--隐藏 -->
      <div v-if="!morecondition">
        <div class="filter">
          <label>{{$t('200002')}}：</label>
          <Select v-model="status" clearable class="searchSelect">
            <Option value>{{$t('1014')}}</Option>
            <Option value="0">{{$t('900938')}}</Option>
            <Option value="1">{{$t('900937')}}</Option>
            <Option value="2">{{$t('500096')}}</Option>
            <Option value="3">{{$t('900936')}}</Option>
            <Option value="4">{{$t('900935')}}</Option>
          </Select>
        </div>
        <div class="filter">
          <label>{{$t('900907')}}</label>
          <DatePicker
            type="daterange"
            :value="dateTime"
            class="searchInput middleWidth"
            @on-change="selectDate"
          ></DatePicker>
        </div>
      </div>
      <!-- 按钮 -->
      <div class="searchBtn">
        <Button type="primary" class="twoWord" icon="ios-search" @click="search()">{{$t('1001')}}</Button>
        <Button type="success" class="twoWord" icon="md-add-circle" @click="add()">{{$t('1002')}}</Button>
        <Button
          type="warning"
          class="twoWord"
          icon="ios-create-outline"
          @click="edit()"
        >{{$t('1003')}}</Button>
        <Button
          type="error"
          class="twoWord intervalRight"
          icon="md-close-circle"
          @click="del()"
        >{{$t('1004')}}</Button>
        <Button
          type="primary"
          class="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>
      </div>
      <!-- 更多条件 按钮组件 -->
      <MoreConbtn @getCon="morecondition = !morecondition" :morecondition="morecondition"></MoreConbtn>
    </div>
    <!-- 数据展示 -->
    <div class="divborder newTableDiv">
      <Table
        class="tableClass"
        @on-current-change="handleRowChange"
        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" v-model="showModal" :styles="{width:'600px'}">
      <p slot="header">
        <span v-if="type==1">{{$t('1002')}}</span>
        <span v-if="type==2">{{$t('1003')}}</span>
      </p>
      <div class="modal_body">
        <div class="filter">
          <label>
            <i>*</i>
            {{$t('100088')}}：
          </label>
          <Select
            :disabled="type==1?false:true"
            v-model="addobj.productid"
            label-in-value
            clearable
            class="searchSelect"
            :on-change="productChange()"
          >
            <Option v-for="item in productlist" :value="item.id" :key="item.id">{{ item.name }}</Option>
          </Select>
        </div>
        <div class="filter">
          <label>{{$t('100089')}}：</label>
          <Input v-model="addobj.productno" class="searchInput" disabled />
        </div>
        <div class="filter">
          <label>{{$t('100090')}}：</label>
          <Input v-model="addobj.drawno" class="searchInput" disabled />
        </div>
        <div class="filter">
          <label>
            <i>*</i>
            {{$t('900933')}}：
          </label>
          <Input v-model="addobj.snno" class="searchInput" />
        </div>
        <div class="filter">
          <label>
            <i>*</i>
            {{$t('99200041')}}：
          </label>
          <Input v-model="addobj.ordernum" class="searchInput" />
        </div>
        <div class="filter">
          <label>
            <i>*</i>
            {{$t('900337')}}：
          </label>
          <Input v-model="addobj.worknum" class="searchInput" />
        </div>
        <div class="filter">
          <label>
            <i>*</i>
            {{$t('99200042')}}：
          </label>
          <Input v-model="addobj.install_quantity" class="searchInput" type="number" />
        </div>
        <div class="filter">
          <label>
            <i>*</i>
            {{$t('500099')}}：
          </label>
          <Input v-model="addobj.order_quantity" class="searchInput" type="number" />
        </div>
        <div class="filter">
          <label>
            <i>*</i>
            {{$t('900934')}}：
          </label>
          <Select v-model="addobj.work_type" clearable class="searchSelect">
            <Option value="1" :v-text="$t('900944')">成品</Option>
            <Option value="2" :v-text="$t('900943')">半成品</Option>
            <Option value="3" :v-text="$t('900942')">返工</Option>
          </Select>
        </div>
        <div class="filter">
          <label>
            <i>*</i>
            {{$t('900941')}}：
          </label>
          <DatePicker type="date" v-model="addobj.deliverydate" class="searchInput"></DatePicker>
        </div>
      </div>
      <div slot="footer">
        <Button size="large" @click="cancel()">{{$t('1033')}}</Button>
        <Button type="primary" v-if="type==1" size="large" @click="saveData(1)">{{$t('1002')}}</Button>
        <Button type="primary" v-if="type==2" size="large" @click="saveData(2)">{{$t('1003')}}</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import moment from 'moment';
import axios from '@/libs/api.request';

export default {
    data () {
        return {
            // 是否展开更多搜索条件
            morecondition: false,
            // 搜索时间范围
            dateTime: [],
            // 搜索条件-产品名称
            productname: '',
            // 搜索条件-图纸号
            productdrawno: '',
            // 搜索条件-工单号
            orderno: '',
            // 搜索条件-生产令号
            produceno: '',
            // 搜索条件-工单状态
            status: '',
            // 返回的数据总数
            total: 0,
            // 页码
            page: 1,
            // 一页展示多少条数据
            pagesize: 10,
            // 表格数据
            tableData: [],
            // 表格列字段对应
            tableColumns: [
                {
                    type: 'index',
                    title: this.$t('1008'),
                    render: (h, params) => {
                        return h(
                            'span',
                            params.index + (this.page - 1) * this.pagesize + 1
                        );
                    },
                    width: '50px'
                },
                {
                    title: this.$t('100088'),
                    key: 'product_name'
                },
                {
                    title: this.$t('100089'),
                    key: 'product_code'
                },
                {
                    title: this.$t('100091'),
                    key: 'product_remark'
                },
                {
                    title: this.$t('900934'),
                    key: 'orderType'
                },
                {
                    title: this.$t('900933'),
                    key: 'partnumber'
                },
                {
                    title: this.$t('900337'),
                    key: 'code'
                },
                {
                    title: this.$t('99200041'),
                    key: 'ordernumber'
                },
                {
                    title: this.$t('99200042'),
                    key: 'install_count'
                },
                {
                    title: this.$t('500099'),
                    key: 'quantity'
                },
                {
                    title: this.$t('500030'),
                    key: 'create_time'
                },
                {
                    title: this.$t('900932'),
                    key: 'delivery_time'
                },
                {
                    title: this.$t('200054'),
                    key: 'status'
                },
                {
                    title: this.$t('600588'),
                    key: 'ok_number'
                },
                {
                    title: this.$t('600589'),
                    key: 'nok_number'
                },
                {
                    title: this.$t('500103'),
                    key: 'num'
                },
                {
                    title: this.$t('900931'),
                    key: 'source'
                }
            ],
            // 是否展示弹出框
            showModal: false,
            // 可选产品下拉列表
            productlist: [],
            // type 为 1 是添加操作 type 为 2 是修改操作
            type: 0,
            // 当前选中的一行
            obj: {},
            // 弹出框中表单对象
            addobj: {},

            action: axios.publicPath + 'cnc/upload/submit?templateName=ProducePlan',
            headers: {
                token: localStorage.getItem('token'),
                timestamp: localStorage.getItem('timestamp'),
                nonce: localStorage.getItem('nonce'),
                sign: localStorage.getItem('sign')
            }
        };
    },
    mounted () {
        const _this = this;
        _this.search();
        _this.tableColumns = _this.$time.initTableTitle(_this.tableColumns);
    },
    methods: {
    // 初始化搜索时间
        initTime () {
            const _this = this;
            let date = new Date();
            let start = _this.$time.timestampToTime(
                date.getTime() - 7 * 24 * 60 * 60 * 1000
            );
            let end = _this.$time.timestampToTime(date.getTime());
            _this.dateTime = [start, end];
        },
        // 监听搜索时间变化
        selectDate (v) {
            this.dateTime = [v[0], v[1]];
        },
        // 搜索
        search () {
            const _this = this;
            // 解构赋值
            let {
                page,
                pagesize,
                productname,
                productdrawno,
                orderno,
                produceno,
                status,
                dateTime
            } = this;
            let params = {
                page,
                pagesize,
                product_name: productname,
                draw_number: productdrawno,
                code: orderno,
                ordernumber: produceno,
                status,
                startTime: dateTime[0],
                endTime: dateTime[1]
            };
            _this.axios
                .request({
                    url: '/cnc/Product/getplanlist',
                    params,
                    methods: 'get'
                })
                .then((res) => {
                    let result = res.data;
                    _this.total = 0;
                    _this.tableData = [];
                    if (result.ret == 1) {
                        if (result.data.length) {
                            _this.total = result.total;
                            _this.initTableData(result.data);
                        }
                    } else {
                        _this.$Message.error(_this.$t('' + result.msg));
                    }
                });
        },
        // 对返回的数据进行处理
        initTableData (tableList) {
            const _this = this;
            let tableData = [];
            if (!Array.isArray(tableList) || !tableList) {
                return false;
            }
            tableList.forEach((item) => {
                let num;
                if (parseInt(item.quantity) <= 0) {
                    num = 0 + '%';
                } else {
                    num = Math.round((item.ok_number / item.quantity) * 100) + '%';
                }
                let status;
                if (item.status == 0) {
                    status = '未排产';
                } else if (item.status == 1) {
                    status = '已排产';
                } else if (item.status == 2) {
                    status = '生产中';
                } else if (item.status == 3) {
                    status = '已完工';
                } else {
                    status = '已终止';
                }
                let orderType;
                if (item.workordertype == 1) {
                    orderType = '成品';
                } else if (item.workordertype == 2) {
                    orderType = '半成品';
                } else if (item.workordertype == 3) {
                    orderType = '返工';
                }
                let source;
                if (item.source == 1) {
                    source = '手动添加';
                } else if (item.source == 2) {
                    source = 'Excel导入';
                } else if (item.source == 3) {
                    source = 'ERP对接';
                }
                tableData.push({
                    id: item.id,
                    product_id: item.product_id,
                    product_name: item.product_name,
                    product_code: item.product_code,
                    draw_number: item.draw_number,
                    product_remark: item.product_remark,
                    workordertype: item.workordertype,
                    orderType: orderType,
                    partnumber: item.partnumber,
                    code: item.code,
                    ordernumber: item.ordernumber,
                    install_count: item.install_count,
                    quantity: item.quantity,
                    create_time: item.create_time_str,
                    delivery_time: item.delivery_time_str,
                    status: status,
                    ok_number: item.ok_number,
                    nok_number: item.nok_number,
                    num: num,
                    source: source
                });
            });
            _this.tableData = tableData;
        },
        // 监听添加按钮
        add () {
            const _this = this;
            // 设置 type 为 1 表示是添加操作
            _this.type = 1;
            // 弹出框显示
            _this.showModal = true;
            // 清空添加对象
            _this.addobj = {};
            // 获取产品下拉列表
            _this.getProductList();
        },
        // 获取产品下拉列表
        getProductList () {
            const _this = this;
            _this.axios
                .request({
                    url: '/config/ProjectProduct/GetProducts',
                    methods: 'get'
                })
                .then((res) => {
                    let result = res.data;
                    _this.productlist = [];
                    if (result.ret == 1) {
                        if (result.data.length) {
                            _this.productlist = result.data;
                        }
                    } else {
                        _this.$Message.error(_this.$t('' + result.msg));
                    }
                });
        },
        // 监听选中表格某一行
        handleRowChange (currentRow) {
            this.obj = currentRow;
        },
        // 弹出框取消按钮
        cancel () {
            this.addobj = {};
            this.showModal = false;
        },
        // 在产品下拉列表中选定一个产品
        productChange () {
            const _this = this;
            let { productlist } = this;
            let productId = _this.addobj.productid;
            if (productlist.length && Array.isArray(productlist)) {
                productlist.forEach(function (item) {
                    if (item.id == productId) {
                        _this.addobj.productno = item.code;
                        _this.addobj.drawno = item.drawingcode;
                    }
                });
            }
        },
        // 监听修改按钮
        edit () {
            const _this = this;
            let { obj } = this;
            // 如果当前没有选中某一行，则跳出函数
            if (JSON.stringify(obj) == '{}') {
                _this.$Message.error(_this.$t('1043'));
                return false;
            }
            // 获取产品下拉列表
            _this.getProductList();
            // 弹出框显示
            _this.showModal = true;
            // type 为 2 表示修改
            _this.type = 2;

            _this.addobj.productid = obj.product_id;
            _this.addobj.drawno = obj.draw_number;
            _this.addobj.productno = obj.product_code;
            _this.addobj.snno = obj.partnumber;
            _this.addobj.ordernum = obj.ordernumber;
            _this.addobj.worknum = obj.code;
            _this.addobj.install_quantity = obj.install_count;
            _this.addobj.order_quantity = obj.quantity;
            _this.addobj.deliverydate = obj.delivery_time;
            _this.addobj.work_type = obj.workordertype + '';
        },
        // 保存弹框数据
        saveData (type) {
            const _this = this;
            let obj = _this.addobj;
            // 必填项表单验证
            if (
                obj.productid == '' ||
        obj.productid == undefined ||
        obj.snno == '' ||
        obj.snno == undefined ||
        obj.ordernum == '' ||
        obj.ordernum == undefined ||
        obj.worknum == '' ||
        obj.worknum == undefined ||
        obj.install_quantity == '' ||
        obj.install_quantity == undefined ||
        obj.order_quantity == '' ||
        obj.order_quantity == undefined ||
        obj.deliverydate == '' ||
        obj.deliverydate == undefined ||
        obj.work_type == '' ||
        obj.work_type == undefined
            ) {
                _this.$Message.error(_this.$t('1063'));
                return false;
            }
            // 组装请求参数
            let data = {
                produceid: obj.productid,
                ordernumber: obj.ordernum,
                partnumber: obj.snno,
                code: obj.worknum,
                quantity: obj.order_quantity,
                workordertype: obj.work_type,
                deliverytime: moment(obj.deliverydate).format('YYYY-MM-DD'),
                autogenerate: 1,
                install_count: obj.install_quantity
            };
            // type 为 1 添加 type 为 2 修改
            if (type == 1) {
                _this.axios
                    .request({
                        url: '/cnc/Product/AddProduceplan',
                        data,
                        method: 'post'
                    })
                    .then((res) => {
                        let result = res.data;
                        if (result.ret == 1) {
                            _this.showModal = false;
                            _this.$Message.success(_this.$t('1055'));
                            _this.page = 1;
                            _this.search();
                        } else {
                            _this.showModal = false;
                            _this.$Message.error(_this.$t('' + result.msg));
                            _this.page = 1;
                            _this.search();
                        }
                    });
            } else if (type == 2) {
                data.id = _this.obj.id;
                _this.axios
                    .request({
                        url: '/cnc/Product/EditProduceplan',
                        data,
                        method: 'post'
                    })
                    .then((res) => {
                        let result = res.data;
                        if (result.ret == 1) {
                            _this.showModal = false;
                            _this.$Message.success(_this.$t('1060'));
                            _this.page = 1;
                            _this.search();
                        } else {
                            _this.showModal = false;
                            _this.$Message.error(_this.$t('' + result.msg));
                            _this.page = 1;
                            _this.search();
                        }
                    });
            }
        },
        // 监听删除事件
        del () {
            if (JSON.stringify(this.obj) === '{}') {
                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 params = { id: this.obj.id };
                        axios
                            .request({
                                url: '/cnc/Product/DeleteProduceplan',
                                params,
                                method: 'post'
                            })
                            .then((res) => {
                                if (res.data.ret === 1) {
                                    this.$Message.success(this.$t('1058'));
                                    this.page = 1;
                                    this.search();
                                } else {
                                    this.$Message.error(this.$t(res.data.msg));
                                    this.search();
                                }
                            });
                    }
                });
            }
        },
        loadexcel () {
            axios
                .request({
                    url: '/config/download/GetTemplate?name=ProducePlan',
                    method: 'get'
                })
                .then((res) => {
                    console.log(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.tableData = this.search();
        },
        changePage (value) {
            this.page = value;
            this.tableData = this.search();
        },
        handleFormatError (file) {
            this.$Message.error(this.$t('950396') + file.name + this.$t('950397'));
        },
        handleSuccess (res, file) {
            if (res.ret == 1) {
                this.$Message.success(this.$t('950398'));
                this.search(this.page, this.pagesize);
            } else {
                if ((res.msg + '').indexOf(',') != -1) {
                    this.page = 1;
                    this.search(this.page, this.pagesize);
                    inittip(res.msg);
                } else {
                    this.$Message.error(this.$t(res.msg));
                }
            }
        },
        handleError () {
            this.$Message.error(this.$t('2010006') + '!');
        }
    }
};
</script>
