<template>
  <div class="bgcolor assignPage">
    <div class="navBarTOP">
      <van-nav-bar class="navBar" left-arrow :title="title" @click-left="onClickLeft" />
    </div>
    <div class="lineGrey"></div>
    <div class="lineGrey"></div>
    <div class="lineGrey"></div>
    <div class="lineGrey"></div>
    <div class="lineGrey"></div>
    <!-- 客资详情 -->
    <assignAwaitDetail :infoData="infoData" v-if="infoData" :source="'JZfollowUp'">
      <div class="info">
        跟进状态：
        <span v-if="infoData.isClose == 1">跟进完成</span>
        <span v-if="infoData.isClose == 0">跟进中</span>
        <span v-if="infoData.isClose == -1">未跟进</span>
        <span v-if="infoData.isClose == 2">已过期</span>
      </div>
      <!-- 转交 -->
      <!--  -->
      <van-button
        v-if="
          infoData.isClose != 1 &&
          infoData.isClose != 2 &&
          postName &&
          postName == '区域家装销售负责人'
        "
        type="info"
        size="small"
        plain
        class="centerBtn"
        @click="showPicker = true">
        转交下属
      </van-button>
    </assignAwaitDetail>
    <!-- 催办历史 -->
    <!-- <hasten
      v-if="infoData && infoData.customerClueInfoUrgeList"
      :hastenList="infoData.customerClueInfoUrgeList"></hasten> -->
    <!-- 历史跟进记录 -->
    <p style="margin: 0 16px 8px; color: #888" v-if="infoData && infoData.userCustomerClueList">
      该客资历史跟进记录
    </p>
    <van-cell-group inset class="cardclewContentCell" v-if="infoData">
      <div style="border-radius: 6px; overflow: hidden">
        <van-cell
          is-link
          v-for="(item, index) in infoData.userCustomerClueList"
          :key="index"
          @click="viewFn(item.userCustomerClueId)">
          <template #title>
            <span class="custom-title">{{ item.nickName }}</span>
          </template>
          <div class="cardContent">
            <p class="textLeft" style="padding-bottom: 0px; margin: 0">{{ item.createTime }}</p>
          </div>
        </van-cell>
      </div>
    </van-cell-group>
    <!-- 跟进任务填写 -->
    <div class="assign" v-if="infoData && infoData.isClose != 1 && infoData.isClose != 2">
      <div class="followUp required">跟进结果</div>
      <div class="taskGather" v-if="taskGather && taskGather">
        <radioGroup :clueOptionList="taskGather"></radioGroup>
      </div>
      <div class="tc" style="padding: 0 16px">
        <van-button class="submitBtn" block type="info" color="#0057ba" @click="onSubmit">
          提交
        </van-button>
      </div>
    </div>
    <!-- 转交下属 -->
    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        title="转交下属"
        show-toolbar
        value-key="nickName"
        :columns="assignTypeData"
        @confirm="confirm"
        @cancel="showPicker = false" />
    </van-popup>
    <!-- 客资跟进历史 -->
    <van-dialog
      v-model="showView"
      title="客资历史"
      show-cancel-button
      cancel-button-text="关闭"
      :show-confirm-button="false"
      class="dialogz">
      <followUpHistory :historyId="historyId" :showView="showView"></followUpHistory>
    </van-dialog>
  </div>
</template>

<script>
import { getCustomerClueInfoById } from '@/api/clew';
import { getDictOption } from '@/api/index';
import assignAwaitDetail from './assignAwaitDetail.vue';
import {
  selectCustomerClueInfoById,
  selectSubUserList,
  allocationSubCustomer,
  insertFollowCustomerClueAnswer,
} from '@/api/assignAwait';
import { mapState } from 'vuex';
import radioGroup from './radioGroup';
import followUpHistory from './followUpHistory';
import store from '@/store';
// import hasten from '@/views/clew/hasten';

export default {
  name: 'assignPage',
  components: {
    assignAwaitDetail,
    radioGroup,
    followUpHistory,
    // hasten,
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
  },
  data() {
    return {
      id: '',
      infoData: null,
      collectionItemList: [],
      title: '',
      postName: '',
      showPicker: false,
      assignTypeData: [],
      taskGather: null, //跟进任务集合
      showView: false,
      historyId: '',
      requiredFlag: true, //问题必填检验
      requiredMessage: '', //必填提示信息
    };
  },
  watch: {},
  activated() {
    this.id = this.$route.query.id;
    this.postName = localStorage.getItem('postName');
    this.getCustomerClueInfoById();
  },
  methods: {
    getCustomerClueInfoById() {
      this.toastLoading(0, '加载中...', true);
      this.id = this.$route.query.id;
      this.collectionAnswerlisd = [];
      this.collectionItemList = [];
      getCustomerClueInfoById({ customerClueInfoId: this.id }).then((response) => {
        this.toastLoading().clear();
        if (response.code == 200) {
          this.infoData = response.data;
          this.title = response.data.name;
          if (response.data.customerClue != null) {
            this.collectionItemList = response.data.customerClue.customerClueItemList;
          } else {
            this.collectionItemList = [];
          }
          //  获取转交下属数据 未跟进状态下
          if (
            this.infoData.isClose != 1 &&
            this.infoData.isClose != 2 &&
            this.postName &&
            this.postName == '区域家装销售负责人'
          ) {
            this.getSelectSubUserList();
          }
          if (this.infoData.isClose != 1 && this.infoData.isClose != 1) {
            this.getSelectCustomerClueInfoById();
          }
          // 当前客资归属人不是当前登录人
          if (this.infoData.sendUserId != localStorage.getItem('userId')) {
            this.$dialog
              .confirm({
                title: '提示',
                message: '该客资已经被转移给其他人',
                showCancelButton: false,
              })
              .then(() => {
                window.location.replace(window.location.origin + this.locationOrigin + '/clew');
              });
          }
        } else {
          this.$toast(res.msg);
        }
      });
    },
    getSelectCustomerClueInfoById() {
      selectCustomerClueInfoById({ customerClueInfoId: this.id }).then((res) => {
        if (res.code == 200) {
          // res.data.customerClue.searchValue.customerClueItemList
          if (res.data.customerClue) {
            res.data.customerClue.customerClueItemList[0].customerClueInfoId = this.id;
            this.taskGather = res.data.customerClue.customerClueItemList;
          }
        } else {
          this.$toast(res.msg);
        }
      });
    },
    getSelectSubUserList() {
      selectSubUserList().then((res) => {
        if (res.code == 200) {
          this.assignTypeData = res.data ? res.data : [];
        } else {
          this.$toast(res.msg);
        }
      });
    },
    confirm(value) {
      this.$dialog
        .confirm({
          title: '提示',
          message: '一旦转交出去，则无法再查看，请确认！',
        })
        .then(() => {
          this.toastLoading(0, '加载中...', true);
          allocationSubCustomer({
            userId: value.userId, //	string	用户ID
            customerClueInfoId: this.id, //	string	客资主键ID
          }).then((res) => {
            this.toastLoading().clear();
            if (res.code == 200) {
              this.$toast(res.msg);
              window.location.replace(window.location.origin + this.locationOrigin + '/clew');
            } else {
              this.$toast(res.msg);
            }
          });
        });
    },
    // 查看历史跟进记录
    viewFn(val) {
      //   this.viewTextShow = false;
      this.historyId = val;
      this.showView = true;
    },
    onSubmit() {
      // 没有选择跟进记录
      if (!this.taskGather[0].searchValue) {
        this.$toast('请选择跟进结果');
        return;
      }
      this.requiredFlag = true;
      let customerClueItemList = [];
      // 每一个层级都是一道题的题目，子级就是题，被选中和填写的题要带上题目一块上传（题的同级也要上传）
      // 第一级题目下的题默认都要上传
      let params = { customerClueItemList: [] };
      params.customerClueItemList.push(...this.deepClone(this.taskGather, 0));
      let optionList = this.taskGather[0].customerClueOptionList;
      this.filterOption(optionList, params);
      // 必填验证
      if (this.requiredFlag) {
        this.toastLoading(0, '加载中...', true);
        insertFollowCustomerClueAnswer(params).then((res) => {
          this.toastLoading().clear();
          if (res.code == 200) {
            if (this.$route.query.token != undefined) {
              window.location.replace(window.location.origin + this.locationOrigin + '/clew');
            } else {
              store.dispatch('setRefreshClewPage', true);
              // 返回上一页不会刷新页面
              this.$router.go(-1);
            }
          } else {
            this.$toast(res.msg);
          }
        });
      } else {
        this.$toast(this.requiredMessage);
      }
    },
    filterOption(optionList, params) {
      let copy = null;
      for (let i = 0; i < optionList.length; i++) {
        if (optionList[i].value == 'Y') {
          if (optionList[i].customerClueItemList) {
            // 必填校验
            this.isRequiredFlag(optionList[i].customerClueItemList);
            params.customerClueItemList.push(
              ...this.deepClone(optionList[i].customerClueItemList, 0),
            );
            if (
              optionList[i].customerClueItemList[0] &&
              optionList[i].customerClueItemList[0].customerClueOptionList.length
            ) {
              this.filterOption(
                optionList[i].customerClueItemList[0].customerClueOptionList,
                params,
              );
            }
          }
        }
      }
    },
    deepClone(obj, num) {
      // 检查是否为对象或数组
      if (obj === null || typeof obj !== 'object') {
        return obj; // 基本类型直接返回
      }
      // 创建一个数组或对象
      const copy = Array.isArray(obj) ? [] : {};
      // 遍历对象的每个属性
      for (const key in obj) {
        if (obj.hasOwnProperty(key) && num < 2) {
          // 递归调用深拷贝
          if (key == 'customerClueOptionList' || key == 'customerClueItemList') {
            num = num + 1;
          }
          copy[key] = this.deepClone(obj[key], num);
        }
      }
      return copy;
    },
    isRequiredFlag(optionList) {
      console.log(optionList);
      // 必填类型
      for (let i = 0; i < optionList.length; i++) {
        if (
          (optionList[i].answerType == 'wb' || optionList[i].answerType == 'sz') &&
          optionList[i].isMust == 0
        ) {
          if (!optionList[i].answerValue) {
            this.requiredFlag = false;
            this.requiredMessage = optionList[i].remark;
            return;
          }
        }
      }
    },
    // 校验错误返回信息
    onFailed(errorInfo) {
      console.log('failed', errorInfo);
    },
    onClickLeft() {
      this.$router.go(-1);
    },
  },
};
</script>
<style scoped lang="scss">
.assignPage {
  .assign {
    margin: 10px;
    background-color: #fff;
    padding-bottom: 20px;
    .followUp {
      padding: 16px;
      font-size: 14px;
      font-weight: 600;
    }
  }
}
</style>
<style lang="scss">
.assignPage {
  .van-field__label {
    width: 100px;
    &::before {
      content: '*';
      color: red;
    }
  }
  .centerBtn {
    float: right;
    background: #0057ba;
    border-color: #0057ba;
    color: #fff;
    margin-top: -33px;
    border-radius: 5px;
  }
  .dialogz {
    width: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    height: 72vh;
    .van-dialog__content {
      flex: 1;
      overflow-y: auto;
    }
  }
}
</style>
