<template>
  <d2-container>
	<div v-if="isExpend" class="d2-fl d2-tree-view" >
	  <el-tree highlight-current :data="treeData" :default-expanded-keys="['top']" node-key="alias" :props="defaultProps" @node-click="handleNodeClick">
		<span class="icon-tree" slot-scope="{ node, data }">
				 			<div v-if="data.alias == 'top'">
				 				<i class="fa fa-university"></i>
				 				<span>&nbsp;{{node.label}}</span>
				 			</div>
				 			<div v-if="data.alias == '4'">
				 				<i class="fa fa-building"></i>
				 				<span>&nbsp;{{node.label}}</span>
				 			</div>
					  <div v-if="data.alias == 'son'">
						<i class="fa fa-user-circle"></i>
						<span>&nbsp;{{node.label}}</span>
					</div>
				 </span>
		</el-tree>
	</div>
	<div @click="isExpend = !isExpend" :class="[{'angle-view':isExpend},{'angle-view-none':!isExpend}]">
	  <i :class="['fa', {'fa-angle-left':isExpend},{'fa-angle-right':!isExpend}]"></i>
	</div>
	<div :class="[{'d2-fl':isExpend},{'d2-table-view':isExpend},{'d2-table-view-full':!isExpend}]"  style="overflow: hidden">
	  <div class="d2-table-view-header">
		<el-form size="small" :inline="true" :model="filter" @keyup.enter.native="handleList" class="demo-form-inline">
		  <el-form-item label="商户名称">
			<el-input v-model="filter.orgNm" placeholder="商户名称" clearable/>
		  </el-form-item>
		  <el-form-item label="商户编号">
			<el-input v-model="filter.merchantCode" placeholder="商户编号" clearable/>
		  </el-form-item>
		  <el-form-item>
			<el-button   type="primary" @click="handleList('1')">查询</el-button>
		  </el-form-item>
		</el-form>
	  </div>
	  <div class="d2-table-view-content">
			 <div class="d2-table-view-handle">
				 <el-button  @click="operVisible = !operVisible" :disabled="falg" size="small" icon="el-icon-plus" slot="headerButton">新增</el-button>
				  <el-button   :disabled="isDisabled"  size="small" @click="onMutilDelClick()">批量删除</el-button>
			 </div>
		<d2-crud
				title="商户列表"
				ref="d2Crud"
				:options="tableOptions"
				:loading="loading"
				:columns="columns"
				:data="data"
				:formRules="formRules"
				@edit="handleRowEdit"
				@delete="handleRowRemove"
				:rowHandle="rowHandle"
				selection-row
				@selection-change="handleSelectionChange"> 
				</d2-crud>
	  </div>
	  <div class="d2-table-view-footer">
		<el-pagination
						@current-change="handleCurrentChange"
						@size-change="handleSizeChange"
						:current-page.sync="currentPage"
						:page-size="tableOptions.pageList[0]"
						:page-sizes="tableOptions.pageList"
						layout="total,sizes, prev, pager, next,jumper"
						:total="pagination.total">
		</el-pagination>
	  </div>
	</div>
	<el-dialog
			:title="diaLogName"
			:visible.sync="operVisible"
			@close="clearForm"
			width="50%"
			:close-on-click-modal="false">
		<el-form ref="form" :model="form" label-width="80px" labelPosition="left" :rules="formRules"  >
		<el-row :gutter="20">
			<el-col :span="12">
			<el-form-item label="商户编号" prop="merchantCode">
				<el-input v-model="form.merchantCode" maxlength="30" :disabled="form.orgId? true:false"/>
			</el-form-item>
			</el-col>
			<el-col :span="12">
			<el-form-item label="商户账号" prop="accountNumber">
				<el-input v-model="form.accountNumber" maxlength="6" :disabled="form.orgId? true:false"/>
			</el-form-item>
			</el-col>
			<el-col :span="12">
			<el-form-item label="商户名称" prop="orgNm">
				<el-input v-model="form.orgNm" maxlength="30"/>
			</el-form-item>
			</el-col>
			<el-col :span="12">
			<el-form-item label="商户类型" prop="merchantsType">
				 <el-select v-model="form.merchantsType" placeholder="请选择" style="width: 100%;">
					<el-option label="食堂" value="0"></el-option>
					<el-option label="商店" value="1"></el-option>
				</el-select>
			</el-form-item>
			</el-col>
			<div v-if="form.orgId == '' ">
				<el-col :span="12">
				<el-form-item label="账户密码" prop="password">
					<el-input type="password" v-model="form.password"/>
				</el-form-item>
				</el-col>
			</div>
			<el-col :span="12">
			<el-form-item label="结算周期" prop="settlementInterval">
			    <el-select v-model="form.settlementInterval" placeholder="请选择" style="width: 100%;">
			   	<el-option label="按月结算" value="0"></el-option>
			   	<el-option label="按周结算" value="1"></el-option>
					<el-option label="按日结算" value="2"></el-option>
			   </el-select>
			</el-form-item>
			</el-col>
			<el-col :span="24">
			<el-form-item label="商户描述">
				<el-input type="textarea" maxlength="100" v-model="form.remarks"/>
			</el-form-item>
			</el-col>
		</el-row>
		</el-form>
		<span slot="footer" class="dialog-footer">
			<zl-button :loading="mtLoading" @click="operInstance('form')"/> 
		</span>
	</el-dialog>
  </d2-container>
</template>

<script>
  import { getMerchantList, saveOrUpdataList, getList ,TreeNode,deleteList} from '../../../api/cost/merchant'
  import { tableOptions } from '../../../assets/options'

  export default {
    name: 'system-merchant',
    data () {
			  let checkUserNo = (rule, value, callback) => {
			  let reg = /^\w+$/;
			  if (!reg.test(value)) {
			    return callback(new Error("请输入由数字或字母组成的正确编号"));
			  } else {
			    callback();
			  }
			};
      return {
				isDisabled:false,
				mtLoading:false,
				func:{
					select:false,
					delete:false,
					add:false,
					update:false
				},
				falg:true,
				leaveOverId:[],
				selection:[],
				disabled:false,
				diaLogName:'新增',
				operVisible:false,
        isExpend:true,
        currentPage:1,
        tableOptions,
        loading: false,
        filter: {
          merchantCode: '',
          orgNm: '',
					parentId:'',
          pageSize: 10,
          pageNum: 1
        },
				form:{
					orgId:'',
					orgNm:'',	
					creTm:'',	
					settlementInterval:'',
					remarks:'',	
					merchantCode:'',
					accountNumber:'',
					password:'',
					merchantsType:'',
					parentId:''
				},
        pagination: {
          total: 0
        },
        columns: [
          {
            title: '商户编号',
            key: 'merchantCode',
            minWidth: '180'
          },
          {
            title: '商户名称',
            key: 'orgNm',
            minWidth: '180'
          },
					/* {
						title: '公司代码',
						key: 'company',
						minWidth: '180'
					}, */
          {
            title: '创建日期',
            key: 'creTm',
            minWidth: '180',
            showOverflowTooltip: true
          },
          {
            title: '结算周期',
            key: 'settlementInterval',
            minWidth: '180',
            formatter (row, column, cellValue, index) {
              if(cellValue === '0'){
								return '按月结算'
							}else if(cellValue === '1'){
								return '按周结算'
							}else if(cellValue === '2'){
								return '按日结算'
							}
            }
          },
          {
            title: '备注',
            key: 'remarks',
            minWidth: '180',
          },
        ],
        rowHandle: {
          columnHeader: '操作',
          minWidth: '180',
          align: 'center',
          custom: [
          	{
           		text: '编辑',
           		type: 'primary',
           		size: 'small',
           		emit: 'edit'
           	},
           	{
           		text: '删除',
           		type: 'danger',
           		size: 'small',
           		emit: 'delete'
           	}
           ],

        },
        formRules: {
          merchantCode: [{required: true, validator: checkUserNo, trigger: 'blur'}],
					 accountNumber: [{required: true, validator: checkUserNo, trigger: 'blur'}],
          password:  [{ required: true, message: '请输入新密码', trigger: 'blur' },
				{ min: 6, max: 20, message: '请输入长度为6到20的字母或数字', trigger: 'blur' }
				],
           merchantsType: [ { required: true, message: '请选择商户类型', trigger: 'change' }],
					 settlementInterval:[{required: true, message: '请选择结算周期', trigger: 'change'}],
           orgNm: [{required: true, message: '请输入商户名称', trigger: 'blur'}],
          // phone: [{required: true, message: '请输入联系电话', trigger: 'blur'}],
          // orgCode: [{required: true, message: '请输入公司编号', trigger: 'blur'}],
        },
        currentParentId:'',
	     	treeData:[],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        data: []
      }
    },
    methods: {
      handleNodeClick(data) {
				if(data.alias !=='top'){
					this.falg = true
					this.filter.parentId = data.id
				}else{
					this.falg = false
					this.filter.parentId = ''
					this.form.parentName = data.name
					this.form.parentId = data.id
				}
        this.handleList()
      },
      handleTreeNode () {
       TreeNode({
        }).then(res=>{
          this.treeData = JSON.parse(res.msgDat)
          /* this.filter.parentId = this.treeData[0].id
          this.form.parentId = this.treeData[0].id
					this.form.parentName = this.treeData[0].name */
          this.handleList()
        })
				 this.handleList()
      },
      handleList (val) {
        if(val){this.filter.pageNum=1
        this.currentPage = 1}
      this.loading = true
        getMerchantList(this.filter).then(res => {
          this.loading = false
          this.data = res.merchantPageList.list
          this.pagination.total = res.merchantPageList.total
        }).catch(err => {
          this.loading = false
        })
      },

      handleCurrentChange (val) {
        this.filter.pageNum = val
        this.handleList()
      },
			handleSizeChange (val) {
			this.filter.pageNum = 1
			this.filter.pageSize = val
			this.handleList()
			},
      operInstance(formName) {
					this.$refs[formName].validate((valid) => {
						if (valid) {
							this.mtLoading=true
							saveOrUpdataList(this.form).then(res => {
								this.mtLoading=false
								this.$message({
									message:this.form.orgId === '' ?'新增成功':'编辑成功',
									type: 'success'
								})
								this.operVisible=false
								this.handleTreeNode()
							}).catch(err => {
               this.mtLoading=false
              })
						}
						})
      },
      handleRowEdit ({row, index}) {
				this.diaLogName='编辑'
				let orgId = row.orgId
				getList({orgId}).then(res => {
					 this.form = res.merchantUpdate
					this.operVisible=true
				})
      },
      handleRowRemove ({row, index}) {
       this.delete(row.orgId)
      },
				handleSelectionChange (selection) {
			  this.selection = selection
			},
			 onMutilDelClick(){
				  	this.isDisabled = true
				 setTimeout(() => {
				   this.isDisabled = false
				 }, 2000)
			  if(!this.selection.length){
			    this.$message({
			      message: '请选择记录',
			      type: 'success'
			    })
					return false
			  } 
				this.leaveOverId=[]
				 this.selection.forEach((item,index)=>{
				 this.leaveOverId.push(item.orgId)
			 })
			 this.leaveOverId=this.leaveOverId.join(",")
			 this.delete(this.leaveOverId)
			},
      delete(orgId){
				this.$confirm('确定删除此记录?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'error'
				}).then(() => {
					deleteList({
						orgId
					}).then(res=>{
						this.$message({
							message: '删除成功',
							type: 'success'
						})
						this.handleTreeNode()
					})
				}) 
			},
			clearForm(){
				this.mtLoading=false
				this.disabled=false
				this.diaLogName='新增'
				this.form={
					orgId:'',
					orgNm:'',	
					creTm:'',	
					settlementInterval:'',
					remarks:'',	
					merchantCode:'',
					accountNumber:'',
					password:'',
					merchantsType:'',
					parentId:this.form.parentId
				}
			},
			/* 	getFunction () {
			  this.$GetFunction({
			    menuUrl:this.$route.path
			  }).then(res=>{
			    res.data.forEach(item=>{
			      if (item.functionType === 'add') {
			        if (item.remarks === 'true') {
			          this.func.add = true
			        } else {
			          this.func.add = false
			        }
			      } else if(item.functionType === 'select') {
			        if (item.remarks === 'true') {
			          this.func.select = true
			        } else {
			          this.func.select = false
			        }
			      }else if(item.functionType === 'update') {
			        if (item.remarks === 'true') {
			          this.$set(this.rowHandle.custom,0,
			            {
			              text: '编辑',
			              type: 'primary',
			              size: 'small',
			              emit: 'edit'
			            },
			          )
			
			        }
			      }else if(item.functionType === 'delete') {
			        if (item.remarks === 'true') {
			          this.$set(this.rowHandle.custom,this.rowHandle.custom.length,
			            {
			              text: '删除',
			              type: 'danger',
			              size: 'small',
			              emit: 'delete'
			            }
			          )
			        }
			      }
			    })
			  })
			} */
    },
    mounted () {
			//this.getFunction ()
      this.tableOptions = this.$calcTableHeight(tableOptions,40)
      this.filter.pageSize = this.tableOptions.pageList[0]
      this.handleTreeNode()
    }
  }
</script>
