<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyName" :placeholder="$t('project.inputProName')"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getProject">{{$t('base.query')}}</el-button>
				</el-form-item>
				<el-form-item style="float:right;" v-if="user.parentId == 1 && user.subordinateType == 0">
					<el-button type="primary" @click="handleAdd">{{$t('base.add')}}</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="list" highlight-current-row v-loading="listLoading" :height="tableHeight" style="width: 100%;">
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="projectName" :label="$t('project.proName')" width="250" sortable>
                <template slot-scope="scope">
                    <el-link :underline="false" type="primary" @click="toDetail(scope.row)">{{scope.row.projectName}}</el-link>
				</template>
			</el-table-column>
            <el-table-column prop="ownerCompanyName" :label="$t('project.assName')" sortable>
			</el-table-column>
            <el-table-column prop="customCompaniesStr" :label="$t('project.cusName')" sortable>
			</el-table-column>
            <el-table-column prop="manager" :label="$t('project.manager')" width="100" align="center" sortable>
			</el-table-column>
			<el-table-column prop="indate" :label="$t('project.indate')" width="200" align="center" sortable>
			</el-table-column>
			<el-table-column :label="$t('base.operate')" width="150" align="center" v-if="user.parentId == 1 && user.subordinateType == 0">
				<template slot-scope="scope">
					<el-button type="danger" size="small" @click="invalid(scope.row.id)" v-if="scope.row.isDelete != 1">{{$t('project.invalid')}}</el-button>
                    <span style="color:red" v-else>{{$t('project.expired')}}</span>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :page-sizes="[20 , 50 , 80 , 100]"
                :page-size="20"
                layout="total, sizes, prev, pager, next"
                :total="total"
                style="float:right;">
            </el-pagination>
		</el-col>

        <!--新增界面-->
		<el-dialog :title="$t('project.addPro')" v-if="addFormVisible" :visible.sync="addFormVisible" :close-on-click-modal="false" customClass='customWidth'>
			<el-form :model="addForm" label-width="120px" :rules="formRules" ref="addForm">
                <el-col :span="24">
                    <el-form-item :label="$t('project.proName')" prop="projectName">
                        <el-input v-model="addForm.projectName" autocomplete="off" :placeholder="$t('project.inputProName')" style="width:510px"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item :label="$t('project.moldName')" prop="mold">
                        <el-select v-model="addForm.mold" @change="companyChange" clearable filterable multiple :placeholder="$t('project.inputMoldName')" value-key='id' style="width:510px">
                            <el-option v-for="item in molds" :key="item.id" :label="item.modelName" :value="item">
                                <span style="float: left">{{ item.modelName }}</span>
                                <span style="float: right; color: #8492a6; font-size: 6px;margin-right:17px;">{{ item.produceCompany }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item :label="$t('project.manager')" prop="managerId">
                        <el-select v-model="addForm.managerId" clearable filterable :placeholder="$t('project.inputManager')" value-key='id' style="width:510px">
                            <!-- <el-option v-for="item in charger" :key="item.id" :label="item.username" :value="item">
                            </el-option> -->
                            <el-option v-for="item in charger" :key="item.id" :label="item.username" :value="item">
                                <span style="float: left">{{ item.username }}</span>
                                <span style="float: right; color: #8492a6; font-size: 13px;">{{ item.companyName }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">{{$t('el.messagebox.cancel')}}</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">{{$t('el.messagebox.confirm')}}</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'

	export default {
		data() {
            const msg = (rule, value, callback) => {
                if (!value) {
                    switch(rule.field) {
                        case "projectName":
                            return callback(new Error(this.$t('project.inputProName')));
                            break;
                        case "mold":
                            return callback(new Error(this.$t('project.inputMoldName')));
                            break;
                        case "managerId":
                            return callback(new Error(this.$t('project.inputManager')));
                            break;
                        default:
                            callback();
                    } 
                } else {
                    callback();
                }
            };
			return {
				filters: {
					keyName: ''
                },
                user: JSON.parse(sessionStorage.getItem('user')),
                charger: [],
                molds: [],

				list: [],
				total: 0,
                page: 1,
                size: 20,
                listLoading: false,
                tableHeight: 0,

                formRules: {
					projectName: [
						{ required: true, validator: msg, trigger: 'blur' }
                    ],
                    mold: [
                        { required: true, validator: msg, trigger: ['blur','change'] }
                    ],
                    managerId: [
                        { required: true, validator: msg, trigger: ['blur','change'] }
                    ]
                },
                
                addFormVisible: false, //新增界面是否显示
				addLoading: false,
				//新增界面数据
				addForm: {
					projectName: '',
                    mold: [],
                    managerId: ''
				}

			}
		},
		methods: {
            //获取基础数据
            getMsg(){
                this.http.post(this.port.project.getUserById, {
                    companyIds: this.user.companyId,
                    id: this.user.id
                } , res => {
                    if (res.code == "ok") {
                        this.charger = res.data;
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.$message({
                        message: error,
                        type: 'error'
                    });
                })

                //获取模具
                this.getMoulds();
            },

            //获取模具
            getMoulds(){
                this.http.post(this.port.mold.modelList, {
                    parentId: this.user.parentId,
                    id: this.user.id
                }, res => {
                    if (res.code == "ok") {
                        this.molds = res.data;
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.$message({
                        message: error,
                        type: 'error'
                    });
                })
            },

			//分页
			handleCurrentChange(val) {
				this.page = val;
				this.getProject();
            },

            handleSizeChange(val) {
                this.size = val;
				this.getProject();
            },
            
			//获取项目列表
			getProject() {
				this.listLoading = true;
				this.http.post(this.port.project.projectList, {
                    keyName: this.filters.keyName,
                    pageNum: this.page,
                    pageSize: this.size,
                }, res => {
                    this.listLoading = false;
                    if (res.code == "ok") {
                        var list = res.data.list;
                        for(var i in list){
                            var customCompaniesStr = "";
                            for(var j in list[i].customCompanies){
                                if(j == list[i].customCompanies.length -1){
                                    customCompaniesStr += list[i].customCompanies[j].companyName;
                                } else {
                                    customCompaniesStr += list[i].customCompanies[j].companyName + "、";
                                }
                            }
                            list[i].customCompaniesStr = customCompaniesStr;
                        }
                        this.list = list;
                        this.total = res.data.total;
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.listLoading = false;
                    this.$message({
                        message: error,
                        type: 'error'
                    });
                })
            },

            //详情
            toDetail(row) {
                this.$router.push('/project/' + row.id);
            },

            invalid(id) {
                this.http.post(this.port.project.invalidProject, {
                    id: id,
                    isDelete: 1,
                }, res => {
                    if (res.code == "ok") {
                        this.getProject();
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.$message({
                        message: error,
                        type: 'error'
                    });
                })
            },

            //选择公司切换人员
            companyChange() {
                var param = {} ,
                    str = this.user.companyId;
                for(var i in this.addForm.mold){
                    str += "," + this.addForm.mold[i].produceCompanyId;
                }
                param.companyIds = str;
                param.id = this.user.id
                this.http.post(this.port.project.getUserById, param , res => {
                    if (res.code == "ok") {
                        this.charger = res.data;
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.$message({
                        message: error,
                        type: 'error'
                    });
                })
            },

            //显示新增界面
			handleAdd() {
                //重新获取一下模具
                this.getMoulds();
				this.addFormVisible = true;
				this.addForm = {
					projectName: '',
                    mold: [],
                    managerId: ''
				};
            },

            //新增
			addSubmit() {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
                        var cId = "",
                            cName = "",
                            mId = "";

                        for(var i in this.addForm.mold){
                            if(cId.indexOf(this.addForm.mold[i].produceCompanyId) == -1){
                                cId += this.addForm.mold[i].produceCompanyId + ",";
                                cName += this.addForm.mold[i].produceCompanyName + ",";
                            }
                            mId += this.addForm.mold[i].id + ","
                        }

                        cId = cId.substring(0,cId.length-1);
                        cName = cName.substring(0,cName.length-1);
                        mId = mId.substring(0,mId.length-1);

                        this.addLoading = true;
                        this.http.post(this.port.project.addProject, {
                            projectName: this.addForm.projectName,
                            customerCompanyIds: cId,
                            customerCompanyNames: cName,
                            manager: this.addForm.managerId.username,
                            managerId: this.addForm.managerId.id,
                            modelIds: mId,
                            flag: 0
                        } , res => {
                            this.addLoading = false;
                            if (res.code == "ok") {
                                this.addFormVisible = false;
                                this.$message({
                                    message: this.$t('prompt.success2'),
                                    type: 'success'
                                });
                                this.getProject();
                            } else {
                                this.$message({
                                    message: res.msg,
                                    type: 'error'
                                });
                            }
                        }, error => {
                            this.addLoading = false;
                            this.addFormVisible = false;
                            this.$message({
                                message: error,
                                type: 'error'
                            });
                        })
					}
				});
			},
        },
        created() {
            let height = window.innerHeight;
            this.tableHeight = height - 210;
            const that = this;
            window.onresize = function temp() {
                that.tableHeight = window.innerHeight - 210;    
            };
        },
		mounted() {
            this.getMsg();
			this.getProject();
		}
	}
</script>