<template>
  <div class="main_wrap">
    <div class="top_bg">
      <div class="title">报备中心</div>
    </div>
    <div class="service_wrap">
      <service-item :order-info="orderInfo"></service-item>
    </div>
    <div class="chat_list" ref="chatList">
      <!--ai对话框 s -->
      <div v-for="(item, index) in recordList" :key="index">
        <template v-if="item.messageType == 4">
          <div class="top_tip_wrap">为了快速解决问题，请选择下方咨询类型</div>
          <div class="ai_chat" >
            <div class="ai_left">
              <img class="report_ai" src="@/assets/report/report_ai.png" alt="">
            </div>
            <div class="ai_right">
              <div class="ai_title">{{ orderInfo?.driverName }}你好，请选择报备内容</div>
              <ul>
                <li v-for="_item in item.content" :key="_item.id" @click="addReportHandler(_item)">“{{_item.name}}”</li>
              </ul>
            </div>
          </div>
        </template>
        <template v-if="[2, 3].includes(Number(item.messageType))">
          <!--ai对话框 e -->
          <div class="tip_wrap">{{item.createTime}}</div>
          <!--客服对话框 s -->
          <div class="customer_item mb20">
            <div class="customer_left">
              <img class="profile_photo mr" src="@/assets/report/report_customer.png" alt="">
            </div>
            <div class="common_right customer_cls">
              <div class="customer_status">{{item.reportConfigName}}</div>
              <div class="response_con">{{item.remark}}</div>
            </div>
          </div>
        </template>
        <template v-if="item.messageType == 1">
          <!--服务人员对话框 e -->
          <div class="tip_wrap">{{item.createTime}}</div>
          <!--服务人员对话框 s -->
          <div class="server_item mb20">
            <div class="common_right service_cls">
              <div class="service_status">{{item.reportConfigName}}</div>
              <div class="response_con">{{item.remark}}</div>
            </div>
            <div class="customer_left">
              <img class="profile_photo ml" v-if="type == 1" src="@/assets/report/report_dispatch.png" alt="">
              <img class="profile_photo ml" v-else src="@/assets/report/report_driver.png" alt="">
            </div>
          </div>
          <!--服务人员对话框 e -->
        </template>
      </div>
    </div>

    <report-list-item :report-list.sync="reportList" @getReport="getReportHandler" />

    <van-popup ref="addReportModal" v-model="addReportShow" :close-on-click-overlay="false" closeable duration="0" round position="bottom">
      <div class="dialog_wrap">
        <img class="add_report_bg" src="@/assets/report/add_report_bg.png" alt="">
        <div class="report_content">
          <template v-if="currentInfo.component == 'time'">
            <!--预约时间报备 s -->
            <div class="report_title">
              <img class="dot" src="@/assets/report/add_report_dot.png" alt="">
              <span>预约时间</span>
            </div>
            <div class="report_time_content" @click="showDatetime = true">
              <div class="report_time_left">
                <img class="add_report_time" src="@/assets/report/add_report_time.png" alt="">
                <span>{{appointTime || '请选择时间'}}</span>
              </div>
              <img class="report_arrow" src="@/assets/report/add_report_arrow.png" alt="">
            </div>
            <!--预约时间报备 e -->
          </template>
          <template v-if="currentInfo.component == 'address'">
            <!--修改地址报备 s -->
            <div class="report_title">
              <img class="dot" src="@/assets/report/add_report_dot.png" alt="">
              <span>修改事发地</span>
            </div>
            <div class="report_time_content" @click="goPage('addressMap')">
              <div class="report_time_left">
                <img class="add_report_time" src="@/assets/report/add_report_address.png" alt="">
                <span>{{address || '请选择地址'}}</span>
              </div>
              <img class="report_arrow" src="@/assets/report/add_report_arrow.png" alt="">
            </div>
            <!--修改地址报备 e -->
          </template>
          <div class="report_title">
            <img class="dot" src="@/assets/report/add_report_dot.png" alt="">
            <span>补充报备内容</span>
          </div>
          <div class="report_common_content">
            <textarea class="report_textarea" id="text-input" rows="4" placeholder="点击这里输入补充报备内容" v-model.trim="remark"></textarea>
<!--            <van-field-->
<!--              v-model="remark"-->
<!--              class="report_textarea"-->
<!--              placeholder="点击这里输入补充报备内容" />-->
          </div>
        </div>
        <div class="report_btn" @click="saveHandler">
          提交报备
        </div>
      </div>
    </van-popup>

    <van-popup v-model="showDatetime" round position="bottom">
      <van-datetime-picker
        class="dataTime"
        v-if="showDatetime"
        v-model="appointTime"
        type="datetime"
        @confirm="onConfirm"
        @cancel="showDatetime = false"
      />
    </van-popup>
  </div>
</template>

<script>
  import { getReportListByOrder, reportHistory, newOrderReporting, getOrderInfo } from "@/api/report"
  import { myMixins} from "@/utils/myMixins";
  import {timeFormat} from "@/utils/common";
  import reportListItem from '@/views/report/components/report-list-item'
  import serviceItem from "@/views/report/components/service-item"
  import {Dialog, Toast} from "vant";
  export default {
    name: "reportIndex",
    components: { serviceItem, reportListItem },
    mixins: [myMixins],
    data() {
      return {
        addReportShow: false,
        remark: '',
        showDatetime: false,
        appointTime: '',
        address: '',
        lat: '',
        lng: '',
        reportList: [],
        recordList: [],
        orderInfo: {},
        type: '',   // 1 调度   2 司机
        currentInfo: '',
        userOrderId: '',
        userOrderCode: '',
        driverId: '',
        clickFlag: true,
      }
    },
    async mounted() {
      const urlParams = new URLSearchParams(window.location.search);
      this.userOrderId = this.$route.query.userOrderId || urlParams.get('userOrderId');
      this.userOrderCode = this.$route.query.userOrderCode || urlParams.get('userOrderCode');
      this.type = this.$route.query.type || urlParams.get('type');
      this.driverId = this.$route.query.driverId || urlParams.get('driverId');
      await this.getReportList();
      await this.getDetail();
      await this.getRecordList();
      await this.scrollToBottom();
    },
    activated() {
      let addressSession = sessionStorage.getItem('reportAddress');
      if(addressSession) {
        let _obj = JSON.parse(addressSession)
        this.address = _obj.startPoiAddress;
        this.lat = _obj.startLat;
        this.lng = _obj.startLng;
        this.adCode = _obj.adCode;
      }
    },
    methods: {
      // 添加滚动方法
      scrollToBottom() {
        this.$nextTick(() => {
          const container = this.$refs.chatList
          container.scrollTop = container.scrollHeight
        })
      },
      async getRecordList() {
        let recordList = await reportHistory({
          userOrderId: this.userOrderId,
          userOrderCode: this.userOrderCode,
          driverId: this.driverId,
          source: Number(this.type),
        })
        this.recordList = recordList.data;
      },
      async saveHandler() {
        if( this.clickFlag ) {
          let data = {
            source: Number(this.type),
            reportContent: this.remark,
            userOrderId: Number(this.userOrderId),
            reportConfigId: this.currentInfo.id,
            userOrderCode: this.userOrderCode,
            driverId: this.driverId,
          }
          if(this.currentInfo.component == 'time') {
            if( !this.appointTime ) {
              Toast('预约时间不能为空')
              return
            }
            if( new Date(this.appointTime).getTime() <= new Date().getTime() ) {
              Toast('预约时间不能小于当前时间')
              return
            }
            data.time = this.appointTime
          }
          if(this.currentInfo.component == 'address') {
            if( !this.address ) {
              Toast('地址不能为空')
              return
            }
            data.address = this.address
            data.lat = this.lat;
            data.lng = this.lng;
          }
          if( !this.remark ) {
            Toast('备注内容不能为空')
            return
          }
          this.clickFlag = false;
          try {
            await newOrderReporting(data)
            Dialog.alert({
              title: '提示',
              message: "报备添加成功"
            }).then(async () => {
              await this.getRecordList()
              this.addReportShow = false
              this.scrollToBottom();
              this.initDialogData();
              this.clickFlag = true
            });
          } finally {
            this.clickFlag = true
          }
        }
      },
      initDialogData() {
        this.appointTime = '';
        this.address = '';
        this.lat = '';
        this.lng = '';
        this.remark = '';
      },
      addReportHandler(data) {  // 点击添加报备弹框
        this.currentInfo = data;
        this.addReportShow = true
      },
      getReportHandler(data) {  // 点击获取当前报备信息
        this.recordList.push({
          messageType: 4,
          content: data.child
        })
        this.scrollToBottom();
      },
      async getDetail(){  // 订单详情
        if(this.userOrderId) {
          let result = await getOrderInfo({
            userOrderId: this.userOrderId,
            userOrderCode: this.userOrderCode
          })
          this.orderInfo = result.data
        } else {
          this.orderInfo = {}
        }

      },
      async getReportList() {   // 报备大类
        let res = await getReportListByOrder({
          orderId: this.userOrderId
        });
        this.reportList = res.data
      },
      onConfirm(data) {
        this.appointTime = timeFormat(new Date(data))
        this.showDatetime = false;
      }
    }
  }
</script>

<style lang="scss" scoped>
  #app {
    background: #F9FCFF !important;
  }
  .main_wrap {
    width: 100%;
    height: 100%;
    background: #F9FCFF !important;
    display: flex;
    flex-direction: column;
  }
.top_bg {
  width: 100%;
  height: 162px;
  background: #334885;
  .title {
    color: #fff;
    text-align: center;
    padding-top: 52px;
    font-size: 17px;
    line-height: 24px;
  }
}
.service_wrap {
  margin-top: -75px;
  margin-bottom: 20px;
}
.chat_list {
  flex: 1;
  overflow: auto;
  .top_tip_wrap {
    color: #7C8698;
    text-align: center;
    font-size: 13px;
  }
  .tip_wrap {
    color: #7C8698;
    text-align: center;
    font-size: 13px;
    margin-bottom: 10px;
  }
  .ai_chat {
    padding: 25px 10px 20px;
    display: flex;
    .ai_left {
      .report_ai {
        width: 44px;
        height: 44px;
        margin-right: 12px;
      }
    }
    .ai_right {
      .ai_title {
        color: #203152;
        font-size: 15px;
        font-weight: 600;
        margin-bottom: 15px;
      }
      li {
        font-size: 13px;
        color: #267EF0;
        line-height: 18px;
        margin-bottom: 15px;
        font-weight: bold;
      }
      li::before {
        content: "";
        display: inline-block;
        width: 8px;
        height: 8px;
        background-color: #5680FA;
        border-radius: 50%; /* 圆形 */
        margin-right: 10px;
      }
    }
  }
}

/*客服人员，服务人员对话弹框样式 s*/
  .profile_photo {
    width: 44px;
    height: 44px;
  }
  .mr {
    margin-right: 10px;
  }
  .ml {
    margin-left: 10px;
  }
  .mb20 {
    margin-bottom: 20px;
  }
  .customer_item {
    display: flex;
    padding-left: 10px;
    padding-right: 64px;
    .customer_left {
    }
  }
  .common_right {
    padding: 11px 13px;
    flex: 1;
    .customer_status::before {
      content: "";
      display: inline-block;
      width: 8px;
      height: 8px;
      background-color: #5680FA;
      border-radius: 50%; /* 圆形 */
      margin-right: 10px;
    }
    .customer_status {
      font-size: 14px;
      color: #267EF0;
      line-height: 20px;
      font-weight: bold;
    }
    .service_status {
      font-size: 14px;
      color: #F07926;
      line-height: 20px;
      font-weight: bold;
    }
    .service_status::before {
      content: "";
      display: inline-block;
      width: 8px;
      height: 8px;
      background-color: #F07926;
      border-radius: 50%; /* 圆形 */
      margin-right: 10px;
    }
  }
  .customer_cls {
    border-radius: 0px 6px 6px 6px;
    background: #E3F0FF;
  }
  .service_cls {
    background: #FAEBD8;
    border-radius: 0px 6px 6px 6px;
  }
  .server_item {
    display: flex;
    padding-right: 10px;
    padding-left: 64px;
  }
  .response_con {
    font-size: 13px;
    color: #242A37;
    line-height: 18px;
    font-weight: bold;
    margin-top: 5px;
  }
  /*客服人员，服务人员对话弹框样式 e*/
  .dialog_wrap {
    .add_report_bg {
      width: 100%;
      height: 76px;
    }
    .report_content {
      width: calc(100% - 12px);
      margin: -30px auto 0;
      padding-right: 14px;
      padding-left: 20px;
      box-sizing: border-box;
      background: #fff;
      position: relative;
      padding-top: 25px;
      border-radius: 10px;
      .report_title {
        font-size: 16px;
        font-weight: 600;
        color: #267EF0;
        line-height: 22px;
        margin-bottom: 10px;
        .dot {
          width: 7px;
          height: 6px;
          margin-right: 12px;
        }
      }
      .report_time_content {
        padding: 13px;
        background: #F2F7FF;
        border-radius: 6px;
        border: 1px solid #E2EAF6;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30px;
        .report_time_left {
          font-size: 14px;
          font-weight: bold;
          color: rgba(0, 0, 0, 0.9);
          display: flex;
          align-items: flex-start;
        }
        .add_report_time {
          width: 18px;
          height: 18px;
          margin-right: 8px;
        }
        .report_arrow {
          width: 8px;
          height: 12px;
          margin-left: 5px;
        }
      }
      .report_common_content {
        margin-bottom: 27px;
        .report_textarea {
          width: 100%;
          box-sizing: border-box;
          background: #F8FAFC;
          border-radius: 6px;
          min-height: 95px;
          border: 1px solid #E2EAF6;
          padding: 10px;
          font-size: 13px;
        }
      }
    }
    .report_btn {
      width: calc(100% - 80px);
      height: 46px;
      line-height: 46px;
      background: #005DD5;
      border-radius: 23px;
      color: #FFFFFF;
      font-size: 15px;
      font-weight: bold;
      text-align: center;
      margin: 0 auto 40px;
    }
  }
  ::v-deep .van-popup__close-icon {
    color: #0F458E;
  }
</style>
