<script setup>
import { reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { customInterence } from '@/api/api.js'
import Contactdia from './components/Contactdialog.vue'
import { useList } from  './hooks/customlistHook'

const $router = useRouter()
const $route = useRoute()

const { Role } = useList()

const formRule = {
  /* 客户名称 */
  custom_name:[
    { required: true, message: '客户名称不能为空', trigger: 'blur' },
  ],
  /* 社会信用码 */
  code:[
    { required: true, message: '社会信用码不能为空', trigger: 'blur' },
  ],
  /* 客户状态 */
  cuStatus:[
    { required: true, message: '客户状态不能为空', trigger: 'blur' },
  ],
  /* 客户类型 */
  custype:[
    { required: true, message: '客户类型不能为空', trigger: 'blur' },
  ],
  /* 行业 */
  trade:[
    { required: true, message: '行业不能为空', trigger: 'blur' },
  ],
  /* 客户来源 */
  from:[
    { required: true, message: '客户来源不能为空', trigger: 'blur' },
  ],
  /* 销售 */
  sales:[
    { required: true, message: '所属销售不能为空', trigger: 'blur' },
  ],
  /* 备注 */
  // addreason:[
  // 	{ required: true, message: '备注不能为空', trigger: 'blur' },
  // ],
}


const companyId = ref($route.query.id)
const activeNames = ref(['1'])//默认展开
const regionType = ref('')
const basicInfo = ref({})//领取的客户基本信息
const pickForm = reactive({
  cuStatus:'试用',
  custype:'',
  trade:'',
  from:'',
  sales:Number(localStorage.getItem('AdminId'))||'',
  addreason:''
})
const authList = ref([])
/* 获取客户详情信息 */
function getDetail() {
  customInterence.customDetail({
    CompanyId:companyId.value
  }).then(res => {
  
    if(res.Ret === 200) {
      regionType.value=res.Data.Item.RegionType
      
      let ficcform = res.Data.FiccItem;//ficc添加的信息
      let basicform = res.Data.Item;//客户基本信息
      let raiform = res.Data.RaiItem;//权益添加的信息
      /* 基础表单 */
      basicInfo.value = {
        custom_name:basicform.CompanyName,
        code:basicform.CreditCode,
        province:basicform.Province,
        city:basicform.City,
        CompanyProductId:res.Data.CreateAuth == 1?ficcform.CompanyProductId:raiform.CompanyProductId,
        cuStatus:res.Data.CreateAuth == 1?ficcform.Status:raiform.Status,
        custype:res.Data.CreateAuth == 1?'ficc':'权益',
        trade:res.Data.CreateAuth == 1?ficcform.IndustryName:raiform.IndustryName,
        from:res.Data.CreateAuth == 1?ficcform.Source:raiform.Source,
        sales:res.Data.CreateAuth == 1?ficcform.SellerName:raiform.SellerName,
        addreason:res.Data.CreateAuth == 1?ficcform.Reasons:raiform.Reasons
      }

      pickForm.custype = basicInfo.value.custype=='ficc'?'权益':'ficc';
      if(res.Data.CreateAuth == 1) { //ficc创建客户
        /* 处理权限列表格式 */
        let auth = [];
        ficcform.PermissionList.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,
            ...item,
          }
          auth.push(obj)
        })
        authList.value = auth;
      }else if (res.Data.CreateAuth == 2){ //权益创建客户
        /* 处理权限列表格式 */
        let auth = [];
        raiform.PermissionList.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,
            ...item,
          }
          auth.push(obj)
        })
        authList.value = auth;
      }

      getAuthBasic();
    }
  })
}
getDetail()


/* 获取基本权限信息 */
const authListRai = ref([])
function getAuthBasic() {
  customInterence.authList({
    NoUpgrade:true
  }).then(res => {
    if(res.Ret === 200) {
      let newArr = [];
      res.Data.List.length&&res.Data.List.forEach(item => {
        let obj = {
          checkAll:false,
          isIndeterminate:item.ClassifyName === '宏观经济'?true:false,
          ...item,
        }
        newArr.push(obj)
      })
      authListRai.value = newArr;
    }
  })
}


/* 获取客户来源数据 */
const fromArr = ref([])//客户来源
function getCustomerSourceList(){
  customInterence.customerSourceList().then(res=>{
    if(res.Ret===200){
      fromArr.value = res.Data.List
    }
  })
}
getCustomerSourceList()


/* 获取销售 */
const salesArr = ref([])
function getSale() {
  customInterence.saleslist().then(res => {
    if(res.Ret === 200) {
      salesArr.value = res.Data.List;
    }
  })
}
getSale()


/* 根据类型获取行业 */
const tradeArr = ref([])
function getIndustry() {
  customInterence.getindustry({
    Classify:pickForm.custype
  }).then(res => {
    if(res.Ret === 200) {
      tradeArr.value = res.Data.List || [];
    }
  })
}

/* 选择行业先校验是否选择了客户类型提示  */
function slideTrade(e) {
  if(!pickForm.custype) {
    ElMessage.warning('请先选择客户类型！')
  }
}


/* 确定 */
const pickFormRef = ref(null)
const diaform = ref({
  name:'',
  sex:1,
  telCode:'86',
  tel1:'',
  tel2:'',
  mail:'',
  post:'',
  desiger:'',
  depart:'',
  carte:'',
  Source:'pick_custom',
})
const isAddContact = ref(false)//是否添加联系人
const isShowclose = ref(false)//是否显示取消
function saveHandle() {
  pickFormRef.value.validate((valid) => {
    if (valid) {
      
      //判断是否选择了权限，默认勾选的也算上
      let checkArr = [];
      authListRai.value.forEach(item => {
        checkArr.push(...item.CheckList)
      })
      console.log(checkArr);
      
      if(!checkArr.length) {
        ElMessage.warning('请选择权限')
        return
      }
      isAddContact.value = true;
    }
  })
}

/* 添加联系人之后再领取客户 */
function cancelConcatdia(type) {
  
  isAddContact.value = false;
  if(type === 1) {
    let checkArr = [];
    authListRai.value.forEach(item => {
      if(item.CheckList.length) {
        checkArr.push(item.CheckList)
      }
    })
    if(checkArr.length) {
      let PermissionIds = checkArr.flat(2).join(',');
      let params = {
        CompanyId: Number(companyId.value),
        IndustryId: pickForm.trade,
        Reasons: pickForm.addreason,
        SellsId: pickForm.sales,
        Source: pickForm.from,
        Status: pickForm.cuStatus,
        CompanyType:pickForm.custype,
        PermissionIds
      }
      customInterence.Pick(params).then(res => {
        if(res.Ret === 200) {
          ElMessage.success(res.Msg);
          $router.replace({
            path:'/customList'
          })
        }
      })
    }else {
      ElMessage.warning('权限设置不能为空')
    }
  }else {
    ElMessage.warning('领取失败')
  }
}

/* 取消 */
function cancelPick() {
  $router.go(-1);
}


/* 选择全选或取消全选 */
function handleCheckAll(item) {
  // 取到所有的子菜单id
  let ids = item.Items.map(item =>{
    return item.ChartPermissionId
  })
  item.CheckList = item.checkAll ? ids : [];
      item.isIndeterminate = false;
}
/* 复选框組选中时 */
function handleChecked(item) {
  let len = item.CheckList.length;
  item.checkAll = len === item.Items.length;
  item.isIndeterminate = len > 0 && len < item.Items.length;
}


watch(
  () => pickForm.custype,
  () => {
    getIndustry();
  }
)

</script>
<template>
  <div class="pickCustom_container">
		<div class="left_form_cont">
			<ul class="detail_item">
				<li>
					<label style="marginRight:60px;width:80px;textAlign:right;display:inline-block;">客户名称</label>
					<span style="width:400px;display:inline-block;">{{basicInfo.custom_name}}</span>
				</li>
				<li>
					<label style="marginRight:60px;width:80px;textAlign:right;display:inline-block;">社会信用码</label>
					<span style="width:400px;display:inline-block;">{{basicInfo.code}}</span>
				</li>
				<li>
					<label style="marginRight:60px;width:80px;textAlign:right;display:inline-block;">客户地址</label>
					<span style="width:400px;display:inline-block;">{{basicInfo.province+'/'+basicInfo.city}}</span>
				</li>
				<li>
					<label style="marginRight:60px;width:80px;textAlign:right;display:inline-block;">客户状态</label>
					<el-radio border :label="basicInfo.cuStatus" style="width:184px;marignRight:200px;" v-model="basicInfo.cuStatus">{{basicInfo.cuStatus=='试用'?'试用（2个月）':basicInfo.cuStatus}}</el-radio>
				</li>
				<li>
					<label style="marginRight:60px;width:80px;textAlign:right;display:inline-block;">客户类型</label>
					<span style="width:400px;display:inline-block;">{{basicInfo.custype}}</span>
				</li>
				<li>
					<label style="marginRight:60px;width:80px;textAlign:right;display:inline-block;">行业</label>
					<span style="width:400px;display:inline-block;">{{basicInfo.trade}}</span>
				</li>
				<li>
					<label style="marginRight:60px;width:80px;textAlign:right;display:inline-block;">客户来源</label>
					<span style="width:400px;display:inline-block;">{{basicInfo.from}}</span>
				</li>
				<li>
					<label style="marginRight:60px;width:80px;textAlign:right;display:inline-block;">所属销售</label>
					<span style="width:400px;display:inline-block;">{{basicInfo.sales}}</span>
				</li>
				<li class="textarea_item" style="width:90%;paddingLeft:15px;">
					<label style="display:block;marginBottom:20px;fontSize:16px;position:relative;">
						权限设置
					</label>
					<ul class="menu_lists">
						<li v-for="item in authList" :key="item.ClassifyName" class="menu_item">
							<el-checkbox :indeterminate="item.isIndeterminate" v-model="item.checkAll" disabled style="marginRight:30px;fontWeight:bold;">{{item.ClassifyName+':'}}</el-checkbox>
							<el-checkbox-group v-model="item.CheckList" disabled>
								<el-checkbox v-for="list in item.Items" :label="list.ChartPermissionId" :key="list.ChartPermissionId" class="list_item">{{list.PermissionName}}</el-checkbox>
							</el-checkbox-group>
						</li>
					</ul>
				</li>
			</ul>
			<!-- 可折叠form -->
			<el-collapse v-model="activeNames" style="width:93%;marginTop:50px;">
				<el-collapse-item :title="basicInfo.custype=='ficc'?'权益属性配置':'ficc属性配置'" name="1">
					<el-form
					@submit.prevent 
					inline
					:model="pickForm" 
					:rules="formRule"
					hide-required-asterisk
					ref="pickFormRef" 
					label-width="100px" 
					class="demo-ruleForm">
						<el-form-item label="客户来源" prop="from" style="marginRight:120px;">
								<i style="color:#f00;fontSize:20px;position:absolute;left:-90px;top:10%;">*</i>
								<el-select v-model="pickForm.from" placeholder="请选择客户来源" style="width:400px;" filterable>
									<el-option
										v-for="item in fromArr"
										:key="item.SourceId"
										:label="item.SourceName"
										:value="item.SourceName">
									</el-option>
								</el-select>
							</el-form-item>
						<el-form-item label="客户状态" prop="cuStatus">
							<i style="color:#f00;fontSize:20px;position:absolute;left:-90px;top:10%;">*</i>
							<el-radio-group v-model="pickForm.cuStatus">
								<el-radio border label="试用" style="width:184px;">试用（2个月）</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-form-item label="客户类型" prop="custype" style="marginRight:120px;">
							<i style="color:#f00;fontSize:20px;position:absolute;left:-90px;top:10%;">*</i>
							<span style="width:400px;display:inline-block;fontSize:16px;color:#666;">{{pickForm.custype}}</span>
						</el-form-item>
						<el-form-item label="行业" prop="trade">
							<i style="color:#f00;fontSize:20px;position:absolute;left:-58px;top:10%;">*</i>
							<el-select v-model="pickForm.trade" placeholder="请选择行业" style="width:400px;">
								<el-option
									v-for="item in tradeArr"
									:key="item"
									:label="item.IndustryName"
									:value="item.IndustryId">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="所属销售" prop="sales">
							<i style="color:#f00;fontSize:20px;position:absolute;left:-90px;top:10%;">*</i>
							<el-select v-model="pickForm.sales" placeholder="请选择销售" style="width:400px;" filterable :disabled="Role=='rai_seller'||Role=='ficc_seller'">
								<el-option
									v-for="item in salesArr"
									:key="item.AdminId"
									:label="item.RealName"
									:value="item.AdminId">
								</el-option>
							</el-select>
						</el-form-item>
						
						<el-form-item class="textarea_item" style="width:96%;paddingLeft:26px;">
							<label style="display:block;marginBottom:20px;fontSize:16px;position:relative;color:#666;">
								<i style="color:#f00;fontSize:20px;position:absolute;left:-15px;top:10%;">*</i>
								权限设置
							</label>
							<ul class="menu_lists">
								<li v-for="item in authListRai" :key="item.ClassifyName" class="menu_item">
									<el-checkbox :indeterminate="item.isIndeterminate" v-model="item.checkAll" :disabled="item.ClassifyName === '宏观经济'" @change="handleCheckAll(item)" style="marginRight:30px;fontWeight:bold;">{{item.ClassifyName+':'}}</el-checkbox>
									<el-checkbox-group v-model="item.CheckList" @change="handleChecked(item)">
										<el-checkbox v-for="list in item.Items" :label="list.ChartPermissionId" :key="list.ChartPermissionId" class="list_item" :disabled="list.ChartPermissionId==1">{{list.PermissionName}}</el-checkbox>
									</el-checkbox-group>
								</li>
							</ul>
						</el-form-item>
					</el-form>
				</el-collapse-item>
			</el-collapse>
			<div style="display:flex;justify-content:center;margin:40px 0 0;">
				<el-button type="primary" style="width:80px;marginRight:24px;" @click="saveHandle">确定</el-button>
				<el-button type="primary" plain style="width:80px;" @click="cancelPick">取消</el-button>
			</div>
		</div>
		<!-- 添加联系人弹窗 -->
		<Contactdia
      :id="companyId"
      :title="'新增联系人'"
      :userForm="diaform"
      :custom_name="basicInfo.custom_name"
      :needCard="true"
      :isPickOther="true"
      :isShowclose="isShowclose"
      :regionType="regionType"
      :isAddContact="isAddContact"
      @cancel="cancelConcatdia"
    />
	</div>
</template>
<style scoped lang="scss">
.pickCustom_container {
	padding:30px 40px 60px 60px;
	background: #fff;
	position: relative;
	border: 1px solid #ECECEC;
	border-radius: 4px;
	box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
	font-size: 16px;
	color: #666;
	/* reset */
	:deep(.el-collapse) {
		border: none;
    .el-collapse-item__header {
      display: block;
      border: none;
      font-size: 16px;
      color: #333;
      margin-bottom: 20px;
      text-align: left;
    }
    .el-collapse-item__wrap {
      border: none;
    }
	}
	:deep(.textarea_item .el-form-item__content) {
		width: 100%;
	}
	:deep(.el-form-item .el-checkbox-group) {
		height: 40px;
		line-height: 40px;
	}
	/*  */
	.detail_item {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		li {
			font-size: 16px;
			color: #666;
			margin-bottom: 30px;
			min-width: 545px;
			margin-right: 30px;
			&:last-child {
				margin-bottom: 0;
			}
			// display: flex;
			// align-items: center;
		}
	}
	.menu_lists {
    width: 100%;
		padding: 40px 18px;
		border: 1px dashed #AAB4CC;
		border-radius: 4px;
		.menu_item {
			display: flex;
			// align-items: center;
			margin-bottom: 40px;
			&:last-child {
				margin-bottom: 0;
			}
			.list_item {
				margin-right: 30px;
				&:last-child {
					margin-right: 0;
				}
			}
		}
	}
}
</style>