<script setup name="AddReportInfo">
import moment from 'moment'
import {ref,reactive, computed} from 'vue'
import { useRouter } from 'vue-router'
import apiReport from '@/api/report'
import { showToast } from 'vant'
import { useWindowSize } from '@vueuse/core'
import ListClassify from './ListClassify.vue'
import CooperUserSelect from './CooperUserSelect.vue'
import InheritReportSearch from './InheritReportSearch.vue'


const router=useRouter()

const { width, height } = useWindowSize()

const props = defineProps({
  id: {
    type: Number,
    default: 0,
  },
  defaultData: {
    type: Object,
    default: null
  }
})
const emit = defineEmits(['close','confirm'])


const classifyNameLabel = computed(() => {
  if(!reportBaseInfo.classifys.length) return  ''

  return reportBaseInfo.classifys.map(_ => _.text).join('/')
})
const relationVarietyLabel = computed(() => {
  if(!reportBaseInfo.relationVariety.length) return  ''

  return reportBaseInfo.relationVariety.map(_ => _.PermissionName).join(',')
})
const cooperationUsersLabel = computed(() => {
  if(!reportBaseInfo.cooperationUsers.length) return  ''

  return reportBaseInfo.cooperationUsers.map(_ => _.NodeName).join(',')
})
const authorLabel = computed(() => {
  if(!reportBaseInfo.author.length) return  ''

  return reportBaseInfo.author.join(',')
})



console.log(props.defaultData)
const reportBaseInfo=reactive({
    addType: props.defaultData?props.defaultData.addType:1,
    inheritId: 0,//继承report id
    classifys: props.defaultData?props.defaultData.classifyName:[],
    relationVariety: [],
    title: props.defaultData?props.defaultData.title:"",
    abstract: props.defaultData?props.defaultData.abstract:"",
    author: props.defaultData?props.defaultData.author:[],
    time: props.defaultData?props.defaultData.createtime:moment().format("YYYY-MM-DD"),
    cooperationType: props.defaultData?props.defaultData.cooperationType:1,//协作方式
    cooperationUsers: props.defaultData?props.defaultData.cooperationUsers:[],
    reportLayout: props.defaultData?props.defaultData.reportLayout:1,//报告布局
    isPublcPublish: props.defaultData?props.defaultData.isPublcPublish:1
})


const authorOpts = ref([])
// 获取作者
function getReportauthor() {
  apiReport.reportAuthorList().then((res) => {
    if (res.Ret == 200) {
      authorOpts.value = res.Data.List || [];
    }
  });
}
getReportauthor()




// 分类弹窗
const showClassify=ref(false)
// 分类筛选
function handleShowClassify() {
  if(props.id) return
  // temReportTitleVal.value=reportBaseInfo.title
  showClassify.value=true
}
function handleConfirmClassify(arr){
    reportBaseInfo.classifys = arr;
    showClassify.value=false

    getRelationPermission()
    handleUpdateBaseInfo()
}
/* 获取关联品种 */
async function getRelationPermission() {
  if(!reportBaseInfo.classifys.length){
    reportBaseInfo.relationVariety = []
    return
  } 

  const res = await apiReport.classifyPermissionList({ClassifyId:reportBaseInfo.classifys[reportBaseInfo.classifys.length-1].id})

    if(res.Ret!==200) return
    reportBaseInfo.relationVariety = res.Data || []
}

function handleUpdateBaseInfo() {
  reportBaseInfo.inheritId = 0;

  if(!reportBaseInfo.classifys.length) return

  
  //获取上次报告
  apiReport.getAuthReportList({
      ClassifyIdFirst: reportBaseInfo.classifys[0].id,
      ClassifyIdSecond: reportBaseInfo.classifys[1]?.id,
      ClassifyIdThird: reportBaseInfo.classifys[2]?.id,
      CurrentIndex: 1,
      PageSize:1,
      Keyword:'',
    }).then((res) => {
      if (res.Ret !== 200) return;
      if (!res.Data.List) {
        reportBaseInfo.addType===2 && showToast('该分类暂无报告')
        
        return false;
      }

      if(reportBaseInfo.addType===1) { //默认只带出作者
        reportBaseInfo.author = res.Data.List
          ? res.Data.List[0].Author.split(",")
          : [''];
      }else {
        chooseInheritReport(res.Data.List[0])
      }
    });
}

/* 选择继承报告 */
async function chooseInheritReport(item) {
  const { Id,Title,Abstract,Author,CollaborateType,ReportLayout,IsPublicPublish,ClassifyIdFirst,ClassifyIdSecond,ClassifyIdThird,ClassifyNameFirst,ClassifyNameSecond,ClassifyNameThird } = item;

  reportBaseInfo.title = Title;
  reportBaseInfo.abstract = Abstract;
  reportBaseInfo.author = Author
        ? Author.split(",")
        : "";;
  reportBaseInfo.cooperationType = CollaborateType;
  reportBaseInfo.inheritId = Id;
  reportBaseInfo.reportLayout = ReportLayout;
  reportBaseInfo.isPublcPublish = IsPublicPublish;
  reportBaseInfo.classifys = [
      {
          id:ClassifyIdFirst,
          text:ClassifyNameFirst,
      },
      {
          id:ClassifyIdSecond,
          text:ClassifyNameSecond,
      },
      {
          id:ClassifyIdThird,
          text:ClassifyNameThird,
      }
  ]
  
  //继承的章节报告默认带出协作人
  if(CollaborateType===1) {
    reportBaseInfo.cooperationUsers = [];
  }else {
    const res = await apiReport.getRportBase({
      ReportId: Id
    })
    if(res.Ret!==200) return
    
    reportBaseInfo.cooperationUsers = res.Data.GrandAdminList
      ? res.Data.GrandAdminList.map(_ => ({
          NodeId: _.AdminId,
          NodeName: _.AdminName
        }))
      : [];
  }
}



//作者弹窗
const showAuthorPop=ref(false)
const temAuthorVal=ref('')
function handleShowAuthor(){
    temAuthorVal.value=reportBaseInfo.author
    showAuthorPop.value=true
}
function handleConfirmAuthor(){
    reportBaseInfo.author=temAuthorVal.value
    showAuthorPop.value=false
}


// 创建日期
const minDate=new Date(2015, 0, 1)
const defaultDate=ref(new Date())
const showCreateTimePop=ref(false)
function handleShowCreatetime(){
    defaultDate.value=new Date(reportBaseInfo.time.replace(/-/g,'/'))
    showCreateTimePop.value=true
}
function handleConfirmCreatime(e){
    reportBaseInfo.time=moment(e).format('YYYY-MM-DD')
    showCreateTimePop.value=false
}


/* 协作人弹窗 */
const isChooseCooperaUserPop = ref(false)
//选择协作人
function handleShowCooperUser() {
  isChooseCooperaUserPop.value = true
}
function handleConfirmCooperaUser(e) {
  reportBaseInfo.cooperationUsers = e;
  
  isChooseCooperaUserPop.value = false
}


/* 继承报告弹窗 */
const isChooseInherReportPop = ref(false)



function close() {
  emit('close')
}
async function handleSave() {
  if(!reportBaseInfo.title) return showToast('请输入报告标题')
  if(!reportBaseInfo.classifys.length) return showToast('请选择报告分类')

  const params = {
    AddType: reportBaseInfo.addType,
    ClassifyIdFirst: reportBaseInfo.classifys[0]
      ? reportBaseInfo.classifys[0].id
      : 0,
    ClassifyNameFirst: reportBaseInfo.classifys[0]?.text,
    ClassifyIdSecond: reportBaseInfo.classifys[1]
      ? reportBaseInfo.classifys[1].id
      : 0,
    ClassifyNameSecond: reportBaseInfo.classifys[1]?.text,
    ClassifyIdThird: reportBaseInfo.classifys[2]
      ? reportBaseInfo.classifys[2].id
      : 0,
    ClassifyNameThird: reportBaseInfo.classifys[2]?.text,
    Title: reportBaseInfo.title,
    Abstract: reportBaseInfo.abstract,
    Author: reportBaseInfo.author.length > 0
            ? reportBaseInfo.author.join(",")
            : "",
    CreateTime: reportBaseInfo.time,
    ReportLayout: reportBaseInfo.reportLayout,
    CollaborateType: reportBaseInfo.cooperationType,
    IsPublicPublish: reportBaseInfo.isPublcPublish,
    InheritReportId: reportBaseInfo.inheritId,
    GrantAdminIdList: reportBaseInfo.cooperationUsers.map(_ => _.NodeId)
  };


  // 编辑
  if (props.id) {

    apiReport.reportEdit({...params,ReportId: Number(props.id)}).then(res => {
      if (res.Ret !== 200) return
      
      emit("confirm", reportBaseInfo);
      return;
    })
  }else {
    
    apiReport.reportAdd(params).then((res) => {
      if (res.Ret === 200) {
  
        let pathInfo = {};
        if(reportBaseInfo.cooperationType===2) {
          pathInfo = {
            path: "/report/chapter/list",
            query: { 
              id: res.Data.ReportId
            },
          }
        }else {
            pathInfo = {
              path: reportBaseInfo.reportLayout===1 
                ? '/report/edit'
                : "/smart_report/edit",
              query: { 
                id: res.Data.ReportId,
                coopType: params.CollaborateType
              },
            }
        }

        // let { href } = router.resolve(pathInfo);
        // window.open(href, "_blank");
        router.push(pathInfo)
  
        close();
      }
    });
  }
}

</script>
<template>
  <div class="reportInfo-page">
    <van-cell-group>
      <van-field name="radio" label="报告类型">
        <template #input>
          <van-radio-group 
            v-model="reportBaseInfo.addType" 
            direction="horizontal" 
            @change="handleUpdateBaseInfo"
            :disabled="id?true:false"
          >
            <van-radio :name="1">新增</van-radio>
            <van-radio :name="2">继承</van-radio>
          </van-radio-group>
        </template>
      </van-field>
    </van-cell-group>
    <van-cell-group>
      <van-cell
        required
        title="报告分类"
        :label="classifyNameLabel"
        :is-link="id?false:true"
        @click="handleShowClassify"
      />
    </van-cell-group>
    <van-cell-group v-if="reportBaseInfo.relationVariety.length">
      <van-cell
        title="关联品种"
        :label="relationVarietyLabel"
      />
    </van-cell-group>
    <van-cell-group>
      <van-field 
        v-model="reportBaseInfo.title"
        label="报告标题"
        placeholder="请输入报告标题"
        input-align="right"
      >
        <template #button v-if="reportBaseInfo.addType===2&&!id">
          <van-button size="small" type="primary" @click="isChooseInherReportPop=true">选择继承报告</van-button>
        </template>
      </van-field>
    </van-cell-group>
    <van-cell-group>
      <van-field
        v-model="reportBaseInfo.abstract"
        rows="2"
        autosize
        label="报告摘要"
        type="textarea"
        placeholder="请输入摘要"
        input-align="right"
      />
    </van-cell-group>
    <van-cell-group>
      <van-cell
        required
        title="报告作者"
        :value="authorLabel"
        is-link
        @click="handleShowAuthor"
      />
     
    </van-cell-group>
    <van-cell-group>
      <van-cell
        required
        title="创建时间"
        :value="reportBaseInfo.time"
        is-link
        @click="handleShowCreatetime"
      />
    </van-cell-group>
    <van-cell-group>
      <van-field name="radio" label="协作方式">
        <template #input>
          <van-radio-group 
            v-model="reportBaseInfo.cooperationType" 
            direction="horizontal"
            :disabled="id||reportBaseInfo.addType===2"
          >
            <van-radio :name="1">个人</van-radio>
            <van-radio :name="2">多人协作</van-radio>
          </van-radio-group>
        </template>
      </van-field>
    </van-cell-group>
    <van-cell-group v-if="reportBaseInfo.cooperationType===2">
      <van-cell
        title="协作人"
        :value="cooperationUsersLabel"
        is-link
        @click="handleShowCooperUser"
      />
    </van-cell-group>
    <van-cell-group>
      <van-field name="radio" label="报告布局">
        <template #input>
          <van-radio-group 
            v-model="reportBaseInfo.reportLayout" 
            direction="horizontal"
            :disabled="id||reportBaseInfo.addType===2"
            >
            <van-radio :name="1">常规布局</van-radio>
            <van-radio :name="2">智能布局</van-radio>
          </van-radio-group>
        </template>
      </van-field>
    </van-cell-group>
    <van-cell-group>
      <van-field name="radio" label="公开发布">
        <template #input>
          <van-radio-group v-model="reportBaseInfo.isPublcPublish" direction="horizontal">
            <van-radio :name="1">是</van-radio>
            <van-radio :name="2">否</van-radio>
          </van-radio-group>
        </template>
      </van-field>
    </van-cell-group>

    <div class="bot-btns">
      <van-button class="bot-btn" type="default" @click="close"
        >取消</van-button
      >
      <van-button class="bot-btn" type="primary" @click="handleSave"
        >保存</van-button
      >
    </div>
  </div>


  <!-- 创建日期 -->
  <van-popup
    v-model:show="showCreateTimePop"
    :position="width > 650 ? 'center' : 'bottom'"
    :style="width > 650 ? { width: '400px' } : ''"
    round
  >
    <van-calendar
      :poppable="false"
      :min-date="minDate"
      :default-date="defaultDate"
      v-model:show="showCreateTimePop"
      title="选择创建日期"
      @confirm="handleConfirmCreatime"
      :style="{ height: '500px' }"
    />
  </van-popup>

  <!-- 作者 -->
  <van-popup
    v-model:show="showAuthorPop"
    position="bottom"
    :style="{ height: '100%' }"
  >
    <div class="select-author-pop">
        <van-checkbox-group v-model="temAuthorVal">
            <van-checkbox
                v-for="item in authorOpts"
                :key="item.Id"
                :name="item.ReportAuthor"
            >{{item.ReportAuthor}}</van-checkbox>
        </van-checkbox-group>
        <div class="bot-btns">
            <van-button class="bot-btn" type="default" @click="showAuthorPop=false">取消</van-button>
            <van-button class="bot-btn" type="primary" @click="handleConfirmAuthor">确定</van-button>
        </div>
    </div>
  </van-popup>


  <!-- 分类弹窗 -->
  <van-popup 
      v-model:show="showClassify"
      :position="width>650?'center':'bottom'"
      :style="width>650?{ width: '400px'}:''"
      round
  >
      <ListClassify
        :defaultVal="defaultData?props.defaultData.classifyName:null"
        @close="showClassify=false" 
        @confirm="handleConfirmClassify"
      />
  </van-popup>

  <!-- 协作人弹窗 -->
  <van-popup 
      v-model:show="isChooseCooperaUserPop"
      position="bottom"
      :style="{height: '100%'}"
  >
      <CooperUserSelect
        v-if="isChooseCooperaUserPop"
        :defaultVal="reportBaseInfo.cooperationUsers"
        @close="isChooseCooperaUserPop=false" 
        @confirm="handleConfirmCooperaUser"
      />
  </van-popup>

  <!-- 继承报告弹窗 -->
  <van-popup 
      v-model:show="isChooseInherReportPop"
      position="bottom"
      :style="{height: '100%'}"
  >
      <InheritReportSearch
        v-if="isChooseInherReportPop"
        @close="isChooseInherReportPop=false" 
        @confirm="chooseInheritReport"
      />
  </van-popup>
</template>
<style scoped lang="scss">
.reportInfo-page{
    min-height: 95vh;
    position: relative;
    background: #EDEDED;
    padding-bottom: 140px;
    :deep(.cell-con){
        flex: 2;
    }
    
    :deep(.van-cell-group) {
      margin: 10px 0;
    }
    .bot-btns{
        height: 140px;
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        background-color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
    }
}
.bot-btn{
    width: 315px;
    margin: 0 10px;
}
.input-report-title-pop{
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    background-color: $page-bg-grey;
    
    .bot-btns{
        flex-shrink: 0;
        padding: 20px 0;
        text-align: center;
    }
}
.select-author-pop{
    height: 100%;
    display: flex;
    flex-direction: column;
    .van-checkbox-group{
        padding: $page-padding;
        flex: 1;
        overflow-y: auto;
        .van-checkbox{
            :deep(.van-checkbox__label){
                padding: 32px 0;
                flex: 1;
                border-bottom: 1px solid $border-color;
            }
        }
    }
    .bot-btns{
        flex-shrink: 0;
        padding: 20px 0;
        text-align: center;
    }
}
@media screen and (min-width:$media-width){
    .reportInfo-page{
        height: calc(100dvh - 60px);
        min-height: calc(95vh - 60px);
        .bot-btns{
            bottom: 24px;
        }
    }
    .bot-btn{
        margin: 0 10px;
    }
    .input-report-title-pop{
        .bot-btns{
            padding: 10px 0;
        }
    }
}
</style>
