/**
 * 模板名称:系统操作日志
 * 作者:zhangyy
 * 时间:2023-09-22
 */

<template>
  <div class="logoffManage">
    <!-- 按订单号搜索 -->
    <Row :gutter="10">
      <Form :label-width="80" :model="searchFilter">
        <Row>
          <Col span="6">
            <FormItem label="用户名">
              <Input placeholder="请输入用户名" v-model="searchFilter.userName" clearable/> 
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="状态">
              <Select v-model="searchFilter.reviewStatus" placeholder="请选择审核状态" clearable>
                <Option value="">全部</Option>
                <Option :value="0" label="待审核"></Option>
                <Option :value="1" label="审核通过"></Option>
                <Option :value="2" label="审核拒绝"></Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="10">
            <FormItem label="申请时间">
              <Row>
                <Col span="11">
                  <DatePicker type="date" placeholder="开始时间"
                    format="yyyy-MM-dd"
                    clearable
                    v-model="searchFilter.startDate"
                    @on-change="changeStartTime"/>
                </Col>
                <Col span="2" style="text-align: center">-</Col>
                <Col span="11">
                  <DatePicker type="date" placeholder="截止时间"
                    format="yyyy-MM-dd"
                    clearable
                    v-model="searchFilter.endDate"
                    @on-change="changeEndTime"
                  />
                </Col>
              </Row>
            </FormItem>
          </Col>
          <Col span="2">
            <Button type="primary" style="margin-left: 25px;" @click="initData">搜索</Button>
          </Col>
        </Row>
      </Form>
    </Row>
    <br/>
    <!-- 数据展示 -->
    <el-table class="el-table" ref="shopListTable" :data="promoteUserList" v-loading="dataloading">
	  <!-- 扩展 -->
	  <el-table-column type="expand">
		<template #default="props">
		  <el-table :data="props.row.userCancelList" border>
			  <el-table-column label="用户名" width="180">
			    <template #default="scope">
				   <span>{{scope.row.userName}}</span>
			    </template>
			  </el-table-column>
			  <el-table-column label="昵称" width="180">
			    <template #default="scope">
			  	   <span>{{scope.row.nickName}}</span>
			    </template>
			  </el-table-column>
			  <el-table-column label="是否管理员" width="180">
			    <template #default="scope">
			  	   <span>{{scope.row.isAdminStr}}</span>
			    </template>
			  </el-table-column>
			  <el-table-column label="注销原因" width="180">
			    <template #default="scope">
			  	   <span>{{scope.row.reason}}</span>
			    </template>
			  </el-table-column>
			  <el-table-column label="手机号" width="180">
			    <template #default="scope">
			  	   <span>{{scope.row.phone}}</span>
			    </template>
			  </el-table-column>
			  <el-table-column label="注册时间" width="180" align="center">
			    <template #default="scope">
			  	   <span v-if="scope.row.registerTime">{{formatData(scope.row.registerTime)}}</span>
				   <span v-else>-</span>
			    </template>
			  </el-table-column>
			  <el-table-column label="申请时间" width="180" align="center">
			    <template #default="scope">
			  	   <span v-if="scope.row.applyTime">{{formatData(scope.row.applyTime)}}</span>
				   <span v-else>-</span>
			    </template>
			  </el-table-column>
			  <el-table-column label="审核时间" width="180" align="center">
			    <template #default="scope">
			  	   <span v-if="scope.row.reviewTime">{{formatData(scope.row.reviewTime)}}</span>
				     <span v-else>-</span>
			    </template>
			  </el-table-column>
			  <el-table-column label="审核状态" width="180">
			    <template #default="scope">
			  	   <span>{{ reviewStatus(scope.row.reviewStatus)}}</span>
			    </template>
			  </el-table-column>
			  <el-table-column label="操作" width="210" v-if="pageName!=4">
			    <template #default="scope">
			      <span>
              <Button type="primary" size="small" @click="putRefuseReason(scope.row)"  v-show ="scope.row.reviewStatus === 0">审核</Button>
              <Button type="submit" size="small" @click="checkRefuseReason(scope.row)"  v-show ="scope.row.reviewStatus !== 0">查看备注</Button>
			      </span> 
			    </template>
			  </el-table-column>
		  </el-table>
		</template>
	  </el-table-column>
	  <!-- 扩展 end-->
    <el-table-column label="公司名称">
      <template #default="scope">
        <span>
          {{scope.row.orgName}}
        </span>
      </template>
    </el-table-column>
    <el-table-column label="公司类型">
      <template #default="scope">
        <span>
          {{scope.row.orgType}}
        </span>
      </template>
    </el-table-column>
    <el-table-column label="法定代表人">
      <template #default="scope">
        <span>
          {{scope.row.idName}}
        </span>
      </template>
    </el-table-column>
    <el-table-column label="联系人">
      <template #default="scope">
        <span>
          {{scope.row.contactName}}
        </span>
      </template>
    </el-table-column>
    <el-table-column label="联系方式">
      <template #default="scope">
        <span>
          {{scope.row.contactCell}}
        </span>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
  <div style="margin: 10px;overflow: hidden">
    <div style="float: right;">
      <Page show-elevator :total="parseInt(totalNum)" :current="searchFilter.current" :page-size="searchFilter.limit"  @on-change="changePage"></Page>
    </div>
  </div>
	
	<!-- 详情弹出层 -->
	<Modal v-model="checkRefuseReasonModel" title="查看备注" style="text-align:center;height:50%" width="35%" @on-ok="checkRefuseReasonModel=false">
	  <Form ref="checkRefuseReasonRef" :model="usersDetail" align="left">
	    <FormItem label="备注文字:" prop="remarks">
	      <span>{{usersDetail.remarks || '无'}}</span>
	    </FormItem>
      <FormItem label="备注图片:" >
        <span v-if="imageList.length != 0">
          <span v-for="(item,index) in imageList" :key="index" style="margin:5px">
            <img :src="item"  alt="" style="height:146px"  />
          </span>
        </span>
        <span v-else>无</span>
      </FormItem>
	  </Form>
	</Modal>
	
	<!-- 添加拒绝原因 -->
	<Modal v-model="refuseReasonModel" title="审核" style="text-align:center;height:50%" width="35%" @on-ok="refuseReasonModel=false" footer-hide="false">
	  <Form ref="putRefuseReasonRef" :model="itemChange" :label-width="100" align="left">
	    <FormItem label="备注文字:" prop="remarks">
	      <Input v-model="itemChange.remarks" placeholder="填写输入备注文字" type="textarea" style="width: 260px" :rows="3"></Input>
	    </FormItem>
      <FormItem label="备注图片:" prop="image">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :headers="{'X-AIYANGNIU-SIGNATURE':token}"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview1"
          :before-upload="beforeUpload"
          :on-success="handleAvatarSuccess"
          :file-list="avatarfileList"
          :limit="5"
          :on-remove="handleRemove1">
          <el-icon><Plus /></el-icon>
        </el-upload>
      </FormItem>
    </Form>
    <div v-show="itemChange.isAdmin == 0" align="left"><span style="color: red;">注意：当前账号为管理员身份，若此账号所在组织下仅剩最后一位管理员，则注销账号会一并将组织注销，请谨慎操作。目前此组织下有{{itemChange.adminTotal || 0}}名管理员，{{itemChange.noAdminTotal || 0}}名非管理员。</span></div>
    <div v-show="itemChange.isAdmin == 1" align="left"><span style="color: red;">注意：点击确定按钮，账户将被注销，请谨慎操作。</span></div>
    <div slot="footer" style="text-align:center;">
      <Button type="submit" @click="doModifyApply(itemChange)">拒绝</Button>
      <Button type="primary" @click="passIn(itemChange)" >通过</Button>
    </div>
	</Modal>
	
    <el-dialog :visible.sync="dialogVisible" size="tiny">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent, onMounted, ref ,reactive,getCurrentInstance} from 'vue'
import {manager} from '@/request/api'
import { Message,Modal } from 'view-ui-plus'
import moment from 'moment'
import { reviewStatus } from '@/utils/system/filters'
import { useRoute } from 'vue-router'
import api from "@/request/apiConfig";

export default defineComponent({
  components:{
    
  },
  setup() {
    let {proxy} = getCurrentInstance();
    const token = localStorage.aynUserToken

    const route = useRoute()
    let dataloading = ref(false) //是否在加载中
    let dialogVisible = ref(false)
    let dialogImageUrl = ref('')
    let promoteUserList = ref([])
    let avatarfileList = ref([])
    let imageList = ref([])
    let uploadUrl = api.apiManager + '/manager/images/upload'
    let totalNum = ref(0)
    let refuseReasonModel = ref(false)
    let checkRefuseReasonModel = ref(false)
    let searchFilter = reactive({
      reviewStatus:'',
      userName:'',
      startDate: '',      //订单开始日期(yyyy-MM-dd)
      endDate: '',        //订单结束日期(yyyy-MM-dd)
      offset: 0,
      limit: 10,
      current:1,
    })
    let itemChange = ref({
      id:'',
      orgId:'',
      isAdmin:'',
      noAdminTotal: 0,
      adminTotal: 0,
      remarks: '',
      image:''
    })
    let usersDetail = ref({})
    let imgDefault = require('../../../assets/images/default.png')


    // 格式化日期
    function formatData(date) {
      return moment(date).format("YYYY-MM-DD hh:mm:ss");
    }

	  function handlePictureCardPreview(file) {
		  dialogImageUrl.value = file;
		  dialogVisible.value = true;
		}
		function handlePictureCardPreview1(file) {
		  dialogImageUrl.value = file.url;
		  dialogVisible.value = true;
		}

		//限制上传的图片是jpg并且小于2M大小的图片
		function beforeUpload(file) {
		  const isJPEG = file.type === 'image/jpeg';
		  const isJPG = file.type === 'image/jpg';
		  const isPNG = file.type === 'image/png';
		  const isPDF = file.type === 'image/pdf';
		  const isLt50M = file.size / 1024 / 1024 < 50;
		  if (!isJPG && !isJPEG && !isPNG && !isPDF) {
		    Message.error('上传图片只能是 JPG,JPEG,PNG,PDF 格式!');
		    return false
		  }
		  if (!isLt50M) {
		    Message.error("上传图片大小不能超过 50MB!");
		  }
		  return (isPNG || isJPG || isJPEG) && isLt50M;
		  // return isLt50M;
		}

		//判断是否上传成功
	  function handleAvatarSuccess(res, file) {
		  if (res.code == "101") {
		    let obj={
		      url:file.raw.type.indexOf('image') != -1?res.data:"",
		      type:file.raw.type,
		      fileName:file.raw.name,
		      downloadUrl:res.data
		    }
		    avatarfileList.value.push(obj)
		    let arr = []
		    avatarfileList.value.forEach(item=>{
		      arr.push(item.url)
		    })
		    itemChange.value.image = arr.join('@_@')
		    Message.success(res.message);
		  } else {
		    Message.error("图片上传失败");
		  }
		}

		function handleRemove1(file, fileList) {
		  avatarfileList.value.forEach((item,index) => {
		    if(item.url == file.url){	
			    let arr = []
		      avatarfileList.value.splice(index,1)
          avatarfileList.value.forEach(item=>{
            arr.push(item.url)
          })
          itemChange.value.image = arr.join('@_@')
		    }
		  });
		}

		async function passIn(item){
      Modal.confirm({
        title:'提示',
        content:'确认通过审核？',
        onOk:async()=>{
        console.log(item.id)
          await manager.userCancelReview({
            userCancelId:item.id,reviewStatus:1, image:item.image, orgId:item.orgId, isAdmin:item.isAdmin, remarks:item.remarks
          }).then(res => {
            if (res.code == '101') {
              Message({
                type: 'success',
                message: '操作成功'
              })
              initData()
              refuseReasonModel.value=false
            } else {
              Message.error(res.message || "操作失败")
              refuseReasonModel.value=false
            }
          })
        }
      })
		}

		async function doModifyApply(item){
      await manager.userCancelReview({
			  userCancelId:item.id,reviewStatus:2, image:item.image, orgId:item.orgId, isAdmin:item.isAdmin, remarks:item.remarks,
			}).then(res => {
				if(res.code == 101){
				  Message({
				    type: 'success',
				    message: '操作成功'
				  })
				  initData()
				  refuseReasonModel.value=false
				}else{
				  Message({
				    type: 'error',
				    message: '操作失败'
				  })
				  refuseReasonModel.value=false
				}
			})
    }

    async function userCancelMatter(id){
      await manager.userCancelMatter({
        orgId:id
      }).then(res => {
        if(res.code == 101){
          itemChange.value.adminTotal = res.data.adminTotal
          itemChange.value.noAdminTotal = res.data.noAdminTotal
        }else{
          Message({
            type: 'error',
            message: '操作失败'
          })
        } 				
      })
	  }

		async function initData() {
      if(route.params.searchFilter && undefined!= route.params.searchFilter){
        searchFilter = route.params.searchFilter
        route.params.searchFilter=null
      }
      dataloading.value = true
      await manager.userCancelPage({
        ...searchFilter
      }).then(res => {
        if (res.code == '101') {
          promoteUserList.value = res.data || []
          totalNum.value = res.total || 0
        } else {
          Message.error(res.message || "获取平台用户信息出错")
        }
      })
      dataloading.value = false
    }

    //更改页码
    function changePage(page) {
      searchFilter.offset = (page - 1) * searchFilter.limit
      searchFilter.current =  page
      initData()
    }
    //更改开始时间
    function changeStartTime(time){
      searchFilter.startDate = time
      initData()
    }

    //更改截止时间
    function changeEndTime(time){
      searchFilter.endDate = time
      initData()
    }
    /*=====搜索=====*/
    function searchItem() {
      initData()
    }
    function checkRefuseReason(item) {
      imageList.value = []
      usersDetail.value = item
      if(usersDetail.value.image){
        imageList.value = usersDetail.value.image.split('@_@')
      }
      checkRefuseReasonModel.value = true
    }

    function putRefuseReason(item){
      console.log(item,'item123')
      avatarfileList.value = []
      itemChange.value.id = item.id
      itemChange.value.orgId = item.orgId
      itemChange.value.isAdmin = item.isAdmin
      itemChange.value.remarks = ""
      itemChange.value.image = ""
      userCancelMatter(item.orgId)
      console.log(itemChange.value)
      refuseReasonModel.value = true
    }

    onMounted(()=>{
      initData()
    })

    return {
      reviewStatus,token,dataloading,dialogVisible,dialogImageUrl,promoteUserList,avatarfileList,imageList,uploadUrl,totalNum,refuseReasonModel,checkRefuseReasonModel,searchFilter,itemChange,usersDetail,imgDefault,putRefuseReason,
      formatData,handlePictureCardPreview,handlePictureCardPreview1,beforeUpload,handleAvatarSuccess,handleRemove1,passIn,doModifyApply,userCancelMatter,initData,changePage,changeStartTime,changeEndTime,searchItem,checkRefuseReason,
    }
  },
})
</script>

<style lang="scss" scoped>
.logoffManage{
  padding: 1em;
  .avatar-uploader .el-upload {
	  border: 1px dashed #d9d9d9;
	  border-radius: 6px;
	  cursor: pointer;
	  position: relative;
	  overflow: hidden;
	}
	.avatar-uploader .el-upload:hover {
	  border-color: #409EFF;
	}
	.avatar-uploader-icon {
	  font-size: 20px;
	  color: #8c939d;
	  width: 50px;
	  height: 50px;
	  line-height: 100px;
	  text-align: center;
	}
	.avatar {
	  width: 50px;
	  height: 50px;
	  display: block;
	}
	.imgStyle {
	  width: 100px;
	  height: 100px;
	  img {
	    width: 100%;
	    height: 100%;
	 }
  }
}
</style>