<template>
  <div class="bgcolor complaintDetail">
    <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>
    <!-- 客诉详情 -->
    <infoDetail v-if="infoData" :infoData="infoData" :customerClassify="customerClassifyOption">
    </infoDetail>
    <!-- 客诉记录 -->
    <complaintLog
      v-if="infoData && infoData.customerClueInfoComplaintList.length"
      :customerClueInfoComplaintList="infoData.customerClueInfoComplaintList"></complaintLog>
    <!-- 跟进记录 userCustomerClueList -->
    <!-- 历史跟进记录 -->
    <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">
      <!-- <div class="assign"> -->
      <!-- 来电分类 -->
      <div class="complaintType">
        <div class="typeItem">
          <van-field
            readonly
            clickable
            name="picker"
            :value="customerClassifyValue"
            label="来电分类一"
            placeholder="点击选择来电分类一"
            @click="showPicker1 = true" />
        </div>
        <div class="typeItem">
          <van-field
            readonly
            clickable
            name="picker"
            :value="customerSubClassifyValue"
            label="来电分类二"
            placeholder="点击选择来电分类二"
            @click="showPicker2 = true" />
        </div>
      </div>
      <!-- <div class="followUp required">跟进结果</div> -->
      <div class="taskGather" v-if="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-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>
    <van-popup v-model="showPicker1" position="bottom">
      <van-picker
        show-toolbar
        value-key="dictLabel"
        :columns="customerClassifyOption"
        @confirm="onConfirm1"
        @cancel="showPicker1 = false" />
    </van-popup>
    <van-popup v-model="showPicker2" position="bottom">
      <van-picker
        show-toolbar
        value-key="dictLabel"
        :columns="customerSubClassifyOption"
        @confirm="onConfirm2"
        @cancel="showPicker2 = false" />
    </van-popup>
  </div>
</template>

<script>
import {
  getComplaintCustomerClueInfoById,
  insertCustomerClueAnswerKs,
} from '@/api/complaintDetail';
import infoDetail from './infoDetail.vue';
import complaintLog from './complaintLog.vue';
import { mapState } from 'vuex';
import radioGroup from './radioGroup';
import followUpHistory from './followUpHistory';
import { getDictOption } from '@/api/index';

export default {
  name: 'complaintDetail',
  components: {
    infoDetail,
    complaintLog,
    radioGroup,
    followUpHistory,
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
  },
  data() {
    return {
      id: '',
      infoData: null,
      title: '',
      postName: '',
      taskGather: null, //跟进任务集合
      requiredFlag: true, //问题必填检验
      requiredMessage: '', //必填提示信息
      showView: false,
      historyId: '',
      customerClassifyValue: '',
      customerClassify: '',
      customerSubClassifyValue: '',
      customerSubClassify: '',
      showPicker1: false,
      showPicker2: false,
      customerClassifyOption: [],
      customerSubClassifyOption: [],
    };
  },
  watch: {},
  activated() {
    this.id = this.$route.query.id;
    this.postName = localStorage.getItem('postName');
    this.getComplaintCustomerClueInfoByIdFun();
  },
  methods: {
    async getCustomerClassify() {
      let option = await getDictOption({}, 'customer_classify');
      this.customerClassifyOption = option.data || [];
      // 来电分类一
      let item = this.customerClassifyOption.find(
        (val) => val.dictValue == this.infoData.customerClassify
      );
      this.customerClassifyValue = item.dictLabel || '';
      this.customerClassify = item.dictValue;
    },
    async getCustomerSubClassify() {
      let option = await getDictOption({}, 'customer_sub_classify');
      this.customerSubClassifyOption = option.data || [];
      // 来电分类二
      let item = this.customerSubClassifyOption.find(
        (val) => val.dictValue == this.infoData.customerSubClassify
      );
      this.customerSubClassifyValue = item.dictLabel || '';
      this.customerSubClassify = item.dictValue;
    },
    getComplaintCustomerClueInfoByIdFun() {
      this.toastLoading(0, '加载中...', true);
      this.id = this.$route.query.id;
      getComplaintCustomerClueInfoById({ customerClueInfoId: this.id }).then((response) => {
        this.toastLoading().clear();
        if (response.code == 200) {
          this.infoData = response.data;
          this.title = response.data.name;
          if (this.infoData.isClose != 1) {
            // response.data.customerClue.customerClueItemList[0].customerClueInfoId = this.id;
            this.taskGather = response.data.customerClue.customerClueItemList;
          }
          this.getCustomerClassify();
          this.getCustomerSubClassify();
        } else {
          this.$toast(res.msg);
        }
      });
    },
    onSubmit() {
      // 没有选择跟进记录
      // if (!this.taskGather[0].searchValue) {
      //   this.$toast('请选择跟进结果');
      //   return;
      // }
      this.requiredFlag = true;
      let customerClueItemList = [];
      // 每一个层级都是一道题的题目，子级就是题，被选中和填写的题要带上题目一块上传（题的同级也要上传）
      // 第一级题目下的题默认都要上传
      let params = {
        customerClueItemList: [],
        customerClassify: this.customerClassify,
        customerSubClassify: this.customerSubClassify,
      };
      params.customerClueItemList.push(...this.deepClone(this.taskGather, 0));
      // let optionList = this.taskGather[0].customerClueOptionList;
      this.filterOption(this.taskGather, params);
      console.log(JSON.stringify(params));
      // 必填验证
      if (this.requiredFlag) {
        this.toastLoading(0, '加载中...', true);
        insertCustomerClueAnswerKs(params).then((res) => {
          this.toastLoading().clear();
          if (res.code == 200) {
            this.$toast(res.msg);
            window.location.replace(window.location.origin + '/mobile/clew');
          } else {
            this.$toast(res.msg);
          }
        });
      } else {
        this.$toast(this.requiredMessage);
      }
    },
    filterOption(optionList, params) {
      for (let val = 0; val < optionList.length; val++) {
        if (
          optionList[val].isMust == '0' &&
          optionList[val].searchValue == null &&
          optionList[val].answerType == 'dx'
        ) {
          // 题目必填校验
          this.requiredFlag = false;
          this.requiredMessage = '请选择' + optionList[val].customerClueName;
          return;
        } else if (optionList[val].isMust == '0' && optionList[val].searchValue) {
          let customerClueOptionList = optionList[val].customerClueOptionList;
          for (let i = 0; i < customerClueOptionList.length; i++) {
            if (customerClueOptionList[i].value == 'Y') {
              if (customerClueOptionList[i].customerClueItemList) {
                // 必填校验
                this.isRequiredFlag(customerClueOptionList[i].customerClueItemList);
                let customerClueItemList =
                  params.customerClueItemList[val].customerClueOptionList[i].customerClueItemList;
                customerClueItemList.push(
                  ...this.deepClone(customerClueOptionList[i].customerClueItemList, 0)
                );
                if (customerClueOptionList[i].customerClueItemList[0]) {
                  this.filterOption(customerClueOptionList[i].customerClueItemList, 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].isMust == 0) {
          if (!optionList[i].answerValue) {
            this.requiredFlag = false;
            this.requiredMessage = optionList[i].remark;
            return;
          }
        }
      }
    },
    // 校验错误返回信息
    onFailed(errorInfo) {
      console.log('failed', errorInfo);
    },
    // 查看历史跟进记录
    viewFn(val) {
      //   this.viewTextShow = false;
      this.historyId = val;
      this.showView = true;
    },
    onConfirm1(value) {
      this.customerClassifyValue = value.dictLabel;
      this.customerClassify = value.dictValue;
      this.showPicker1 = false;
    },
    onConfirm2(value) {
      this.customerSubClassifyValue = value.dictLabel;
      this.customerSubClassify = value.dictValue;
      this.showPicker2 = false;
    },
    onClickLeft() {
      this.$router.go(-1);
    },
  },
};
</script>
<style scoped lang="scss">
.complaintDetail {
  .assign {
    margin: 10px;
    background-color: #fff;
    padding-bottom: 20px;
    .followUp {
      padding: 16px;
      font-size: 14px;
      font-weight: 600;
    }
  }
  .taskGather {
    padding-left: 20px;
    .title {
      font-size: 15px;
      font-weight: 600;
      padding: 5px 0;
    }
  }
}
</style>
<style lang="scss">
.complaintDetail {
  .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;
    }
  }
  .van-cell {
    font-size: 15px;
    color: #000;
  }
}
</style>
