<script setup>
import { computed, onMounted, ref } from 'vue'
import { customInterence } from '@/api/api.js'
import { useRoute,useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { filterMoney } from '@/common/js/util'
import Ctimeline from './components/Ctimeline.vue'
import imgPreview from '@/components/imgPreview.vue'
import CustomDtlDialog from './components/CustomDtlDialog.vue'
import {CalculationDate} from '@/utils/CalculationDate'
// import pdf from 'vue-pdf'

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

const companyId = ref($route.query.id)
const contractId = ref($route.query.contractId)
const isLook = ref($route.query.isLook || false)
const companyInfo = ref(JSON.parse(sessionStorage.getItem('companyInfo')) || {})//客户基本信息
const ProductId = ref(0)
const status = ref('')
const reason = ref('')
const contractInfo = ref({})//合同信息
const imglist = []//合同列表图片
const authList = ref([])//权限列表
const diff_time = ref('')
/* 客户信息弹窗 */
const isOpenCustomDtl = ref(false)

/* 获取详情 */
function getCompanyInfo() {
  customInterence.approvalDetail({
    CompanyId:companyId.value,
    CompanyContractId:Number(contractId.value)
  }).then(res => {
    if(res.Ret === 200) {
      ProductId.value=res.Data.Item.ProductId
      /* 处理合同期限 截取一位小数剔除.0 */
      diff_time.value = Number(
        Number((
        (new Date(res.Data.Item.EndDate).getTime())
        -(new Date(res.Data.Item.StartDate).getTime())
        )/(1000*60*60*24*365))
        .toFixed(1).replace(/.0/,''));
      res.Data.Item.StartDate = res.Data.Item.StartDate.replace(/-/g,'.');
      res.Data.Item.EndDate = res.Data.Item.EndDate.replace(/-/g,'.');
      res.Data.Item.Money = filterMoney(res.Data.Item.Money);
      contractInfo.value = res.Data.Item;
      imglist.value = res.Data.Item.ImgUrl.split('#');//合同图片
      /* 权限 */
      let auth = [];
      res.Data.Item.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;
    }
  })
}
getCompanyInfo()

onMounted(() => {
   /* 查看审批 */
  if(isLook.value) {
    status.value = companyInfo.value.ApproveStatus=='已审批'?'通过':companyInfo.value.ApproveStatus;
    reason.value = companyInfo.value.ApproveRemark;
  }
})


/* 确定 */
function ensureHandle() {
  if(status.value == '驳回' && !reason.value) {
    ElMessage.warning('请填写驳回理由！');
  }else {
    customInterence.Approval({
      CompanyId:parseInt(companyId.value),
      Remark:reason.value,
      Status:status.value=='通过'?1:2,
      ProductId:ProductId.value,
    }).then(res => {
      if(res.Ret === 200) {
        ElMessage.success(res.Msg);
        $router.go(-1);
      }
    })
  }
}
/* 取消 */
function cancelHandle() {
  $router.go(-1);
}


const isPreviewimg = ref(false)
const preAct = ref(0)
const isShowToggle = ref(false)//是否显示切换
/* 预览 */
function preview(id,index,img) {
  // $('#'+id).click()
  if(img.indexOf('.pdf')!=-1){
    window.open(img);
  }else if(img.indexOf('.doc')!=-1||img.indexOf('.docx')!=-1){
      window.open('https://view.officeapps.live.com/op/view.aspx?src='+img,'_blank');
  }else{
    let bol = imglist.value.some(item => {
      return item.indexOf('.pdf') != -1
    })
    // 有pdf或图片只有一张
    if(bol || imglist.value.length<=1) {
      isShowToggle.value = false
    }else {
      isShowToggle.value = true
    }
    isPreviewimg.value = true;
  }
}
function closePreview() {
  isPreviewimg.value = false;
}
function togglePre(type) {
  if(type==1) {
    preAct.value--;
    if(preAct.value < 0) {
      preAct.value = imglist.value.length-1;
    }
  }else {
    preAct.value++;
    if(preAct.value > imglist.value.length-1) {
      preAct.value = 0;
    }
  }
}


/* 选择全选或取消全选 */
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;
}


const ContractTermTxt = computed(() => {
  let date = `${contractInfo.value.StartDate}-${contractInfo.value.EndDate}`;
  let calculation = CalculationDate(contractInfo.value.StartDate,contractInfo.value.EndDate);
  let str = contractInfo.value.Quarter ? contractInfo.value.Quarter + `（${date}）` : date + `（${calculation}）`;
  return str
})


</script>
<template>
  <div class="approvalTurn_box">
		<div class="approvalTurn_container">
			<!-- 转正申请 -->
			<div class="card_cont">
				<h3 style="marginRight:18px;fontSize:16px;">
					申请信息 
					<el-button size="mini" type="primary" @click="isOpenCustomDtl=true" style="marginLeft:10px;">客户信息</el-button>
				</h3>
				<div class="history_item">
					<span>待审批内容：试用转正式</span> <span class="contract_type_hint">{{contractInfo.SourceTag}}</span>
					<ul class="detail_item">
						<li>
							<span>合同类型： {{contractInfo.ContractType}}</span>
						</li>
						<li>
							<span style="min-width:450px;marginRight:260px;display:inline-block;">合同期限：{{ContractTermTxt}}</span>
							<span>合同金额：{{contractInfo.Money}}元</span>
						</li>
						<li>
							<span style="min-width:450px;marginRight:260px;display:inline-block;">付款方式：{{contractInfo.PayMethod}}</span>
							<span>付款渠道：{{contractInfo.PayChannel}}</span>
						</li>
						<li v-if="contractInfo.PackageType">
							<p style="min-width:320px;marginRight:260px;display:inline-block;">套餐类型：<span class="setmeal-bg">{{contractInfo.PackageType==1 ?'大套餐':'小套餐'}}</span></p>
						</li>
						<li class="textarea_item" style="width:97%;">
							<label style="display:block;marginBottom:20px;fontSize:16px;position:relative;">
								权限设置
							</label>	
							<ul class="menu_lists">
								<template v-for="item in authList" >
									<li class="menu_item" v-if="item.CheckList.length" :key="item.ClassifyName">
										<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>
								</template>
							</ul>	
						</li>
						<li class="textarea_item" style="width:97%;display:flex">
							<label style="marginRight:17px;fontSize:16px;position:relative;width:112px;">
								查看合同附件
							</label>
							<ul class="img_cont">
								<li v-for="(img,index) in imglist" :key="img" class="img_item">
									<el-image :src="require('@/assets/img/constract/word-icon.png')" style="width:240px;height:180px;" v-if="img.indexOf('.doc')!=-1||img.indexOf('.docx')!=-1" @click="preview('img'+index,index,img)"></el-image>
									<pdf ref="pdf" :src="img" style="width:240px;height:180px;overflow:hidden" v-else-if="img.indexOf('.pdf')!=-1" @click="preview('img'+index,index,img)"></pdf>
									<el-image :src="img" alt="" style="background:#aaa;width:240px;height:180px;" :id="'img'+index" v-else @click="preview('img'+index,index,img)"/>
									<i class="el-icon-zoom-in" style="position:absolute;right:12px;top:12px;color:#fff;" @click="preview('img'+index,index,img)"></i>
								</li>
							</ul>
						</li>
						<li style="marginBottom:20px;">
							<label style="marginRight:40px;fontSize:16px;position:relative;padding-left:18px;">
								<i style="color:#f00;fontSize:20px;position:absolute;left:0;top:2px;">*</i>
								审批状态
							</label>
							<el-radio-group v-model="status" size="medium" :disabled="isLook">
								<el-radio label="通过"></el-radio>
								<el-radio label="驳回" style="marginLeft:0;"></el-radio>
							</el-radio-group>
						</li>
						<li v-if="status=='驳回'">
							<label style="display:block;marginBottom:10px;fontSize:16px;position:relative;padding-left:18px;">
								<i style="color:#f00;fontSize:20px;position:absolute;left:0;top:2px;">*</i>
								驳回理由
							</label>
							<el-input type="textarea" v-model="reason" rows="4" style="width:97%;" placeholder="输入理由" :disabled="isLook"></el-input>
						</li>
						<li style="display:flex;justify-content:center;margin:60px 0 0;" v-if="!isLook">
							<el-button type="primary" style="width:80px;marginRight:24px;" @click="ensureHandle">确定</el-button>
							<el-button  type="primary" plain style="width:80px;" @click="cancelHandle">取消</el-button>
						</li>
					</ul>
				</div>
			</div>
		</div>
		<Ctimeline :id="companyId"></Ctimeline>
		<!-- 图片预览 -->
		<imgPreview
		:isShowToggle="isShowToggle"
		:isPreview="isPreviewimg" 
		:arr="imglist" 
		:actIndex="preAct"
		@close="closePreview"
		@togglePre="togglePre"></imgPreview>
		<!-- 客户基本信息弹窗 -->
		<CustomDtlDialog 
		 :isOpenCustomDtl="isOpenCustomDtl"
		 :companyInfo="companyInfo"
		 @cancelHandle="isOpenCustomDtl=false"
		/>
	</div>
</template>
<style scoped lang="scss">

</style>