<template>
	<div class="Capplydia_container">
	<el-dialog
	:visible.sync="isApply"
	:close-on-click-modal="false"
	:modal-append-to-body='false'
	@close="cancelHandle"
	custom-class="apply_dialog"
	center
	top="5vh"
	v-dialogDrag
	width="1000px">
		<div slot="title" style="display:flex;alignItems:center;">
			<img :src="title=='申请领取'?$icons.pick:title=='申请解冻'?$icons.lock:title=='申请延期'?$icons.delay:''" style="color:#fff;width:16px;height:16px;marginRight:5px;">
			<span style="fontSize:16px;">{{title}}</span>
		</div>
		<div class="dialog_cont">
			<div class="detail_info" v-if="title=='申请领取' || isRoleType=='ficc'">
				<!-- 申请领取 -->
				<template v-if="title=='申请领取'">	
					<div class="info_item">
						<span style="width:50%;">客户名称：{{formdata.CompanyName}}</span>
						<span>客户状态：{{formdata.Status}}</span>
					</div>
					<div class="info_item">
						<span style="width:250px;">原销售：{{formdata.SellerName}}</span>
					</div>
				</template>
				<!-- 申请解冻 -->
				<template v-else-if="title=='申请解冻'">
					<div class="info_item">
						<span style="width:50%;">客户名称：{{formdata.CompanyName}}</span>
						<span style="width:120px">客户状态：{{formdata.Status}}</span>
					</div>
					<div class="info_item">
						<span style="width:250px;">冻结期限：{{formdata.FreezeStartDate}}-{{formdata.FreezeEndDate}}</span>
						<span style="width:120px">到期天数：{{formdata.FreezeExpireDays}}</span>
					</div>
				</template>
				<!-- 申请延期 -->
				<template v-else-if="title=='申请延期'">	
					<div class="info_item">
						<span style="width:50%;">客户名称：{{formdata.CompanyName}}</span>
						<!-- <span style="width:120px">客户状态：{{formdata.Status}}</span> -->
					</div>
						<!-- <div class="info_item">
							<span style="width:250px;">服务期限：{{formdata.StartDate}}-{{formdata.EndDate}}</span>
							<span style="width:120px">到期天数：{{formdata.ExpireDay}}</span>
						</div> -->
					<div class="info_item">
						<span style="width:250px;">请选择需要延期的品种:</span>
					</div>
					<el-table
					:data="authList"
					:span-method="objectSpanMethod"
					@selection-change="handleSelectionChange"
					border	
					max-height="300"
					style="margin-top: 20px">
						<el-table-column v-if="isRoleType" label="所属类目" align="center">
							<template slot-scope="scope">{{scope.row.ClassifyName}}</template>
						</el-table-column>
						<el-table-column :label="isRoleType != 'ficc'?'行业':'品种'" align="center">
							<template slot-scope="scope">{{scope.row.PermissionName}}</template>
						</el-table-column>
						<el-table-column label="状态" align="center">
							<template slot-scope="scope">{{scope.row.Status}}</template>
						</el-table-column>
						<el-table-column label="服务期限" align="center" min-width="200">
							<template slot-scope="scope">{{scope.row.StartDate+'-'+scope.row.EndDate}}</template>
						</el-table-column>
						<el-table-column label="剩余天数" align="center">
							<template slot-scope="scope">{{scope.row.ExpireDay}}</template>
						</el-table-column>
						<el-table-column
							type="selection"
							width="50">
						</el-table-column>
					</el-table>
				</template>
				<!-- 申请解冻和申请领取勾选权限 -->
				<FreezAuthList :autharr="authList" v-if="title!=='申请延期'"/>
			</div>
			<div class="bot_form">
				<div>
					<label style="display:block;marginBottom:10px;fontSize:16px;position:relative;padding-left:18px;">
						<i style="color:#f00;fontSize:20px;position:absolute;left:0;top:20%;">*</i>
						申请理由
					</label>
					<el-input type="textarea" v-model="reason" rows="4" style="width:100%;" placeholder="输入理由"></el-input>
				</div>
			</div>
		</div>	
		<div style="display:flex;justify-content:center;margin:75px 0 50px;">
			<el-button type="primary" style="width:80px;marginRight:24px;" @click="saveHandle">确定</el-button>
			<el-button  type="primary" plain style="width:80px;" @click="cancelHandle">取消</el-button>
		</div>
	</el-dialog>

	<!-- 用户已存在弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="isHaveUser"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      @close="cancelHandle2"
      center
      top="25vh"
      width="700px"
	  v-dialogDrag
    >
      <div style="font-size: 15px; color: #606266; margin-bottom: 10px">
        检测系统中已存在以下联系人 <span v-if="!canMove">（请联系对应销售处理）</span>
      </div>
      <el-table :data="userData" border>
        <el-table-column align="center" label="联系人">
          <template slot-scope="scope">{{ scope.row.RealName }}</template>
        </el-table-column>
        <el-table-column align="center" label="手机号/邮箱" width="300">
          <template slot-scope="scope">
            {{ scope.row.Mobile }}
            {{ scope.row.Mobile && scope.row.Email ? "/" : "" }}
            {{ scope.row.Email }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="销售">
          <template slot-scope="scope">{{ scope.row.SellerRealName }}</template>
        </el-table-column>
        <el-table-column align="center" label="关联客户">
          <template slot-scope="scope">{{ scope.row.CompanyName }}</template>
        </el-table-column>
      </el-table>
      <div style="display: flex; justify-content: center; margin: 30px 0">
        <template v-if="canMove">
          <el-button type="primary" style="margin-right: 24px" @click="moveSale"
            >移动至当前客户</el-button
          >
          <el-button
            type="primary"
            plain
            style="width: 80px"
            @click="cancelHandle2"
            >取消</el-button
          >
        </template>
        <el-button
          type="primary"
          style="width: 100px"
          v-else
          @click="cancelHandle2"
          >知道了</el-button
        >
      </div>
    </el-dialog>
	</div>
</template>

<script>
import { customInterence } from '@/api/api.js'
import FreezAuthList  from './FreezAuthList.vue'
export default {
	name:'',
	components: { FreezAuthList },
	props:{
		/* 客户信息 */
		formdata:{
			type:Object,
			default:{}
		},
		/* 标题 */
		title:{
			type:String
		},
		isApply:{
			type:Boolean
		},
		contactFormData:{
			type:Object,
			default:{}
		}
	},
	watch: {
		formdata(newval) {
			this.formdata = newval;
			this.reason = this.formdata.ApplyReasons || '';
			this.title === '申请延期'&&this.getAuth(this.formdata);
			this.title !== '申请延期'&&this.getAuthAll(this.formdata);
		},
	},
	data () {
		return {
			pickData:{},//如果是申请领取并且移动联系人后提交申请用此数据
			isHaveUser: false, //已存在联系人弹窗
			userData: [], //已存在的联系人
     	 	canMove: "", //是否显示移动按钮
			reason:'',//有申请理由回显
			authList:[],
			selectArr:[],//勾选的品种id
			// isRoleType:''
		};
	},
	methods: {
		/* 提交申请 */
		saveHandle() {
         
			if(!this.reason) {
				this.$message.warning('请填写申请理由！')
			}else {
            let params_public = {};
            if(this.title === '申请解冻' || this.title === '申请领取') {
               /* 处理权限列表 */
               let checkArr = [];
               this.authList.forEach(item => {
                  if(item.CheckList.length) {
                     checkArr.push(item.CheckList)
                  }
               })
               let PermissionIds = checkArr.flat(Infinity).join(',');
               params_public = {
                  ApplyRemark:this.reason,
                  CompanyId:this.formdata.CompanyId,
                  CompanyApprovalId:this.formdata.CompanyApprovalId?parseInt(this.formdata.CompanyApprovalId):0,
                  PermissionIds
               }
            }

				switch (this.title) {
					case '申请延期':
						if(this.selectArr.length || this.isRoleType=='权益') { // 权益不进行校验
							customInterence.applyDelay({
								ApplyRemark:this.reason,
								CompanyId:this.formdata.CompanyId,
								CompanyApprovalId:this.formdata.CompanyApprovalId?parseInt(this.formdata.CompanyApprovalId):0,
								PermissionIds:this.selectArr.join(',')
							}).then(res => {
								if(res.Ret === 200) {
									this.$message.success(res.Msg);
									this.cancelHandle(1);
								}
							})
						}else {
							this.$message.warning('请勾选需要延期的品种！')
						}
						break;
					case '申请解冻':
						console.log(params_public.PermissionIds);
						if(params_public.PermissionIds=='1'){
							this.$message.warning('请选择权限！')
						}else{
							customInterence.applyThaw(params_public).then(res => {
								if(res.Ret === 200) {
									this.$message.success(res.Msg);
									this.cancelHandle(1);
								}
							})
						}
						break;
					case '申请领取':
						if(params_public.PermissionIds!='1'&&params_public.PermissionIds!='') {
							// customInterence.applyPick(params_public).then(res => {
							// 	if(res.Ret === 200) {
							// 		this.$message.success(res.Msg);
							// 		this.cancelHandle(1);
							// 	}
							// })
							this.handleApplyPick(params_public)
						}else{
							this.$message.warning('请选择权限！')
						}
						
						break;
				
					default:
						break;
				}
			}
		},
		// 申请领取 
		async handleApplyPick(pickdata){
			// 从客户审批列表发起的申请
			if(!this.contactFormData.CompanyId){
				let pickRes=await customInterence.applyPick(pickdata)
				if(pickRes.Ret === 200) {
					this.$message.success(pickRes.Msg);
					this.cancelHandle(1);
				}
				return
			}
			let addRes=await customInterence.concactAdd({
				CompanyId:Number(this.contactFormData.CompanyId),
                Email: this.contactFormData.mail || this.contactFormData.mailQY||'',
                DepartmentName: this.contactFormData.depart,
                IsMaker: Number(this.contactFormData.desiger),
                MobileOne: this.contactFormData.tel1 || this.contactFormData.telQY,
                MobileTwo: this.contactFormData.tel2,
                Position: this.contactFormData.post,
                RealName: this.contactFormData.name,
                Sex: Number(this.contactFormData.sex),
                Source: this.contactFormData.Source,
                BusinessCardUrl: this.contactFormData.carte,
                RegionType: this.contactFormData.RegionType,
			})
			if(addRes.Ret===200){
				let pickRes=await customInterence.applyPick(pickdata)
				if(pickRes.Ret === 200) {
					this.$message.success(pickRes.Msg);
					this.cancelHandle(1);
				}
			}else if(addRes.Ret==600){
				// 如果是本客户中存在的联系人直接发起申请
				if(addRes.Data.CompanyId==this.contactFormData.CompanyId){
					let pickRes=await customInterence.applyPick(pickdata)
					if(pickRes.Ret === 200) {
						this.$message.success(pickRes.Msg);
						this.cancelHandle(1);
					}
				}else{
					this.pickData=pickdata
					this.canMove = addRes.Data.HasMove;
					this.userData = [];
					this.userData.push(addRes.Data);
					this.isHaveUser = true;
				}
				
			}
			
			
		},
		//移动联系人
		async moveSale(){
			let userId = this.userData[0].UserId;
      		let SellerId=localStorage.getItem('AdminId')
			let res=await customInterence.moveUser({
				CompanyId: Number(this.contactFormData.CompanyId),
				BusinessCardUrl:this.contactFormData.carte,
				DepartmentName:this.contactFormData.depart,
				Email:this.contactFormData.mail || this.contactFormData.mailQY,
				IsMaker:Number(this.contactFormData.desiger),
				Mobile:this.contactFormData.tel1 || this.contactFormData.telQY,
				Position:this.contactFormData.post,
				RegionType:"",
				RealName:this.contactFormData.name,
				Remark:"",
				SellerId:Number(SellerId),
				Sex:Number(this.contactFormData.sex),
				UserId:Number(userId),
			})
			if(res.Ret===200){
				this.isHaveUser=false
				let pickRes=await customInterence.applyPick(this.pickData)
				if(pickRes.Ret === 200) {
					this.$message.success(pickRes.Msg);
					this.cancelHandle(1);
				}
			}
		},
		//  取消联系人重复弹窗
		cancelHandle2() {
			this.canMove = "";
			this.isHaveUser = false;
		},


		/* 取消弹窗 */
		cancelHandle(type) {
			this.reason = '';
			console.log(type);
			this.$emit('cancelHandle',type);
		},
		// 获取权限   
		getAuth(item) {
			this.authList = [];
			if(!item.CompanyId) return
			customInterence.lookauth({
				CompanyId:item.CompanyId,
				LookType:1
			}).then(res => {
				if(res.Ret === 200) {
					let auth = [];
					res.Data.List ?	res.Data.List.forEach(item=> {
						auth.push(item.Items)
					}) : res.Data.ListRai.forEach(item=> {
						auth.push(item.Items)
					})
					let auth_all = auth.flat(Infinity);
					this.authList = auth_all.filter(auth => {
						return auth.Status === '试用'
					})
					this.getRowSpan();
				}
			})
			this.isLook = true;
		},
		/* 申请解冻 申请领取获取所有权限 */
		getAuthAll(item) {
			if(!item.CompanyId){
				return
			}
			this.authList = [];
			customInterence.allAuth({
				CompanyId:item.CompanyId,
				CompanyType:item.CompanyType
			}).then(res=> {
				if(res.Ret === 200) {
					let auth = [];
					const roleType=localStorage.getItem('RoleType')
                    // let auth_arr = item.CompanyType === 'ficc' ? res.Data.FiccPermissionList : res.Data.PermissionList;
                    let auth_arr = roleType === 'ficc' ? res.Data.FiccPermissionList : res.Data.PermissionList;
					console.log(auth_arr);
					auth_arr.forEach(item=> {
						let obj = {
							checkAll:item.CheckList&&item.CheckList.length===item.Items.length?true:false,
							isIndeterminate:item.CheckList&&item.CheckList.length>0 && item.CheckList.length<item.Items.length,
							defaultAuth:item.CheckList,
							...item,
						}
						auth.push(obj)
					})
					this.authList = auth;
				}
			})
		},
		/* 处理合并数组 */
		getRowSpan() {
			this.rowSpanArr = [];
			/* [2,0,1] */
			this.authList.forEach((item, index) => {
				if (index === 0) {
					this.rowSpanArr.push(1);
					this.position = 0;
				} else {
					if (this.authList[index].ClassifyName === this.authList[index - 1].ClassifyName) {
						this.rowSpanArr[this.position] += 1; //项目名称相同，合并到同一个数组中
						this.rowSpanArr.push(0);
						this.authList[index].ClassifyName = this.authList[index - 1].ClassifyName;
					} else {
						this.rowSpanArr.push(1);
						this.position = index;
					}
				}
			});
		},
		/* 合并行规则 */
		objectSpanMethod({ row, column, rowIndex, columnIndex }) {
			if(this.isRoleType !='ficc') return
			if (columnIndex === 0) {
				const _row = this.rowSpanArr[rowIndex];
					return {
						rowspan: _row,
						colspan: 1
					};
			}
		},
		handleSelectionChange(val) {
		   this.selectArr = val.map((item,index)=>{return item.ChartPermissionId});
      }
	},
	created() {},
	mounted() {
	
	},
	computed: {
			isRoleType(){
				let type = localStorage.getItem('RoleType') || '';
				return type;			
			}
	}
}
</script>
<style lang='scss' >
.Capplydia_container {
	* {box-sizing: border-box;}
	// .apply_dialog {
	// 	position: fixed;
	// 	top: 50%;
	// 	left: 50%;
	// 	transform: translate(-50%,-50%);
	// 	margin-top: 0 !important;
	// }
	.dialog_cont {
		.detail_info {
			border: 1px solid #AAB4CC;
			border-radius: 4px;
			padding: 30px 40px 30px 20px;
			.info_item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				font-size: 16px;
				color: #666;
				margin-bottom: 20px;
				&:last-child {
					margin-bottom: 0;
				}
			}
		}
		.bot_form {
			margin-top: 30px;
		}
	}
}
</style>