<script setup>
import ICON from '@/utils/icon'
import { ElMessage } from 'element-plus'
import { computed, ref, watch } from 'vue'
import { customInterence } from '@/api/api.js'

const props = defineProps({
  /* 客户信息 */
  formdata: {
    type: Object,
    default: {}
  },
  /* 标题 */
  title: {
    type: String
  },
  isApply: {
    type: Boolean
  },
  contactFormData: {
    type: Object,
    default: {}
  }
})
const emits = defineEmits(['cancelHandle'])

const pickData = ref({})//如果是申请领取并且移动联系人后提交申请用此数据
const isHaveUser = ref(false)//已存在联系人弹窗
const userData = ref([])//已存在的联系人
const canMove = ref('')//是否显示移动按钮
const reason = ref('')//有申请理由回显
const authList = ref([])
const selectArr = ref([])//勾选的品种id

const isRoleType = computed(() => {
  return localStorage.getItem('RoleType') || ''
})

watch(() => props.formdata, (newval) => {
  reason.value = props.formdata.ApplyReasons || '';
  props.title === '申请延期' && getAuth(props.formdata);
  props.title !== '申请延期' && getAuthAll(props.formdata);
})

/* 提交申请 */
function saveHandle() {

  if (!reason.value) {
    ElMessage.warning('请填写申请理由！')
  } else {
    let params_public = {};
    if (props.title === '申请解冻' || props.title === '申请领取') {
      /* 处理权限列表 */
      let checkArr = [];
      authList.value.forEach(item => {
        if (item.CheckList.length) {
          checkArr.push(item.CheckList)
        }
      })
      let PermissionIds = checkArr.flat(Infinity).join(',');
      params_public = {
        ApplyRemark: reason.value,
        CompanyId: props.formdata.CompanyId,
        CompanyApprovalId: props.formdata.CompanyApprovalId ? parseInt(props.formdata.CompanyApprovalId) : 0,
        PermissionIds
      }
    }

    switch (props.title) {
      case '申请延期':
        if (selectArr.value.length || isRoleType.value == '权益') { // 权益不进行校验
          customInterence.applyDelay({
            ApplyRemark: reason.value,
            CompanyId: props.formdata.CompanyId,
            CompanyApprovalId: props.formdata.CompanyApprovalId ? parseInt(props.formdata.CompanyApprovalId) : 0,
            PermissionIds: selectArr.value.join(',')
          }).then(res => {
            if (res.Ret === 200) {
              ElMessage.success(res.Msg);
              cancelHandle(1);
            }
          })
        } else {
          ElMessage.warning('请勾选需要延期的品种！')
        }
        break;
      case '申请解冻':
        console.log(params_public.PermissionIds);
        if (params_public.PermissionIds == '1') {
          ElMessage.warning('请选择权限！')
        } else {
          customInterence.applyThaw(params_public).then(res => {
            if (res.Ret === 200) {
              ElMessage.success(res.Msg);
              cancelHandle(1);
            }
          })
        }
        break;
      case '申请领取':
        if (params_public.PermissionIds != '1' && params_public.PermissionIds != '') {
          // customInterence.applyPick(params_public).then(res => {
          // 	if(res.Ret === 200) {
          // 		ElMessage.success(res.Msg);
          // 		this.cancelHandle(1);
          // 	}
          // })
          handleApplyPick(params_public)
        } else {
          ElMessage.warning('请选择权限！')
        }

        break;

      default:
        break;
    }
  }
}

// 申请领取 
async function handleApplyPick(pickdata) {
  // 从客户审批列表发起的申请
  if (!props.contactFormData.CompanyId) {
    let pickRes = await customInterence.applyPick(pickdata)
    if (pickRes.Ret === 200) {
      ElMessage.success(pickRes.Msg);
      cancelHandle(1);
    }
    return
  }
  let addRes = await customInterence.concactAdd({
    CompanyId: Number(props.contactFormData.CompanyId),
    Email: props.contactFormData.mail || props.contactFormData.mailQY || '',
    DepartmentName: props.contactFormData.depart,
    IsMaker: Number(props.contactFormData.desiger),
    MobileOne: props.contactFormData.tel1 || props.contactFormData.telQY,
    MobileTwo: props.contactFormData.tel2,
    Position: props.contactFormData.post,
    RealName: props.contactFormData.name,
    Sex: Number(props.contactFormData.sex),
    Source: props.contactFormData.Source,
    BusinessCardUrl: props.contactFormData.carte,
    RegionType: props.contactFormData.RegionType,
  })
  if (addRes.Ret === 200) {
    let pickRes = await customInterence.applyPick(pickdata)
    if (pickRes.Ret === 200) {
      ElMessage.success(pickRes.Msg);
      cancelHandle(1);
    }
  } else if (addRes.Ret == 600) {
    // 如果是本客户中存在的联系人直接发起申请
    if (addRes.Data.CompanyId == props.contactFormData.CompanyId) {
      let pickRes = await customInterence.applyPick(pickdata)
      if (pickRes.Ret === 200) {
        ElMessage.success(pickRes.Msg);
        cancelHandle(1);
      }
    } else {
      pickData.value = pickdata
      canMove.value = addRes.Data.HasMove;
      userData.value = [];
      userData.value.push(addRes.Data);
      isHaveUser.value = true;
    }

  }


}

//移动联系人
async function moveSale() {
  let userId = userData.value[0].UserId;
  let SellerId = localStorage.getItem('AdminId')
  let res = await customInterence.moveUser({
    CompanyId: Number(props.contactFormData.CompanyId),
    BusinessCardUrl: props.contactFormData.carte,
    DepartmentName: props.contactFormData.depart,
    Email: props.contactFormData.mail || props.contactFormData.mailQY,
    IsMaker: Number(props.contactFormData.desiger),
    Mobile: props.contactFormData.tel1 || props.contactFormData.telQY,
    Position: props.contactFormData.post,
    RegionType: "",
    RealName: props.contactFormData.name,
    Remark: "",
    SellerId: Number(SellerId),
    Sex: Number(props.contactFormData.sex),
    UserId: Number(userId),
  })
  if (res.Ret === 200) {
    isHaveUser.value = false
    let pickRes = await customInterence.applyPick(pickData.value)
    if (pickRes.Ret === 200) {
      ElMessage.success(pickRes.Msg);
      cancelHandle(1);
    }
  }
}

//  取消联系人重复弹窗
function cancelHandle2() {
  canMove.value = "";
  isHaveUser.value = false;
}

/* 取消弹窗 */
function cancelHandle(type) {
  reason.value = '';
  console.log(type);
  emits('cancelHandle', type);
}

// 获取权限
function getAuth(item) {
  authList.value = [];
  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);
      authList.value = auth_all.filter(auth => {
        return auth.Status === '试用'
      })
      getRowSpan();
    }
  })
}

/* 申请解冻 申请领取获取所有权限 */
function getAuthAll(item) {
  if (!item.CompanyId) {
    return
  }
  authList.value = [];
  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)
      })
      authList.value = auth;
    }
  })
}
/* 处理合并数组 */
let rowSpanArr = []
let position = 0
function getRowSpan() {

  /* [2,0,1] */
  authList.value.forEach((item, index) => {

    if (index === 0) {
      rowSpanArr.push(1);
      position = 0;
    } else {
      if (authList.value[index].ClassifyName === authList.value[index - 1].ClassifyName) {
        rowSpanArr[position] += 1; //项目名称相同，合并到同一个数组中
        rowSpanArr.push(0);
        authList.value[index].ClassifyName = authList.value[index - 1].ClassifyName;
      } else {
        rowSpanArr.push(1);
        position = index;
      }
    }
  });
}

/* 合并行规则 */
function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
  if (isRoleType.value != 'ficc') return
  if (columnIndex === 0) {
    const _row = rowSpanArr[rowIndex];
    return {
      rowspan: _row,
      colspan: 1
    };
  }
}

function handleSelectionChange(val){
    selectArr.value = val.map((item,index)=>{return item.ChartPermissionId});
}



</script>

<template>
  <div class="Capplydia_container">
    <el-dialog
      :model-value="props.isApply"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      @close="cancelHandle"
      class="apply_dialog"
      center
      top="5vh"
      draggable
      width="1000px"
    >
      <template #header>
        <div style="display: flex; align-items: center">
          <img
            :src="
              props.title == '申请领取'
                ? ICON.pick
                : props.title == '申请解冻'
                ? ICON.lock
                : props.title == '申请延期'
                ? ICON.delay
                : ''
            "
            style="color: #fff; width: 16px; height: 16px; margin-right: 5px"
          />
          <span style="fontsize: 16px">{{ props.title }}</span>
        </div>
      </template>

      <div class="dialog_cont">
        <div
          class="detail_info"
          v-if="props.title == '申请领取' || isRoleType == 'ficc'"
        >
          <!-- 申请领取 -->
          <template v-if="props.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="props.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="props.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 #default="scope">{{
                  scope.row.ClassifyName
                }}</template>
              </el-table-column>
              <el-table-column
                :label="isRoleType != 'ficc' ? '行业' : '品种'"
                align="center"
              >
                <template #default="scope">{{
                  scope.row.PermissionName
                }}</template>
              </el-table-column>
              <el-table-column label="状态" align="center">
                <template #default="scope">{{ scope.row.Status }}</template>
              </el-table-column>
              <el-table-column label="服务期限" align="center" min-width="200">
                <template #default="scope">{{
                  scope.row.StartDate + "-" + scope.row.EndDate
                }}</template>
              </el-table-column>
              <el-table-column label="剩余天数" align="center">
                <template #default="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="props.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="提示"
      :model-value="isHaveUser"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      @close="cancelHandle2"
      center
      top="25vh"
      width="700px"
      draggable
    >
      <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 #default="scope">{{ scope.row.RealName }}</template>
        </el-table-column>
        <el-table-column align="center" label="手机号/邮箱" width="300">
          <template #default="scope">
            {{ scope.row.Mobile }}
            {{ scope.row.Mobile && scope.row.Email ? "/" : "" }}
            {{ scope.row.Email }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="销售">
          <template #default="scope">{{ scope.row.SellerRealName }}</template>
        </el-table-column>
        <el-table-column align="center" label="关联客户">
          <template #default="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>


<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>