<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">
      <!-- <van-button
        type="info"
        v-if="infoData.customerClueStatus == 0"
        style="
          float: right;
          background: #0057ba;
          border-color: #0057ba;
          color: #fff;
          margin-top: -36px;
          border-radius: 5px;
        "
        size="small"
        plain
        class="centerBtn"
        @click="onstopVisit"
        >转交其他组织</van-button
      > -->
    </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>
    <p v-if="infoData && infoData.isClose == 1" style="padding: 10px 0"></p>
    <!-- 跟进任务填写 -->
    <div
      class="assign"
      v-if="
        infoData && infoData.isClose != 1 && infoData.isClose != 2 && this.infoData.allowFollowUp
      ">
      <!-- <div class="assign"> -->
      <div style="padding: 10px 16px 0 16px; color: red; font-size: 14px">
        400客服已对来电进行分类，若分类有误，可重新分类
      </div>
      <!-- 来电分类 -->
      <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="show" title="转发客资" show-cancel-button :before-close="confirm">
      <p>
        <van-notice-bar wrapable :scrollable="false" text="一旦转交出去，则无法再查看，请确认！" />
      </p>
      <van-row class="serchInput">
        <van-col span="24">
          <van-cell
            class="monthNow selectcell"
            :title="companyName"
            is-link
            arrow-direction="down"
            @click="regionClick" />
        </van-col>
        <van-col span="24">
          <van-cell
            class="monthNow selectcell"
            :title="regionName"
            is-link
            @click="SalesRegionClick"
            arrow-direction="down" />
        </van-col>
        <van-col span="24">
          <van-cell
            class="monthNow selectcell"
            :title="deptName"
            is-link
            @click="SalesDepartmentClick"
            arrow-direction="down" />
        </van-col>
      </van-row>
    </van-dialog>
    <!-- 渠道投诉跟进历史 -->
    <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="remark"
        :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>
    <van-popup v-model="RegionShow" capture position="bottom">
      <van-picker
        :columns="companyList"
        show-toolbar
        value-key="deptName"
        @cancel="RegionShow = false"
        @confirm="onregionConfirm" />
    </van-popup>
    <van-popup v-model="SalesRegionShow" capture position="bottom">
      <van-picker
        :columns="regionList"
        show-toolbar
        value-key="deptName"
        @cancel="SalesRegionShow = false"
        @confirm="onSalesRegionConfirm" />
    </van-popup>
    <van-popup v-model="SalesDepartmentShow" capture position="bottom">
      <van-picker
        :columns="deptList"
        show-toolbar
        value-key="deptName"
        @cancel="SalesDepartmentShow = false"
        @confirm="onSalesDepartmentConfirm" />
    </van-popup>
  </div>
</template>

<script>
import {
  getComplaintCustomerClueInfoById,
  insertCustomerClueAnswerKs,
  customerClassify,
  customerSubClassify,
} 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';
import { updateCustomerClueDept, getDeptInfo } from '@/api/clew';
import store from '@/store';

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: [],
      deptCode: '',
      regionList: [],
      deptList: [],
      companyName: '',
      companyCode: '',
      regionName: '',
      regionCode: '',
      deptName: '',
      show: false,
      RegionShow: false,
      SalesRegionShow: false,
      SalesDepartmentShow: false,
      companyList: [],
      deptForm: { type: '', parentId: '' },
    };
  },
  watch: {},
  activated() {
    this.id = this.$route.query.id;
    this.postName = localStorage.getItem('postName');
    this.getDeptInfo();
    this.getComplaintCustomerClueInfoByIdFun();
  },
  methods: {
    async getCustomerClassify() {
      let option = await customerClassify();
      this.customerClassifyOption = option.data || [];
      // 来电分类一
      let item = this.customerClassifyOption.find(
        (val) => val.dictValue == this.infoData.customerClassify,
      );
      this.customerClassifyValue = item ? item.remark : '';
      this.customerClassify = item ? item.dictValue : '';
      if (this.customerClassify != '') this.getCustomerSubClassify(this.customerClassify);
    },
    async getCustomerSubClassify(parentId) {
      let option = await customerSubClassify({ parentId: parentId });
      this.customerSubClassifyOption = option.data || [];
      // 来电分类二
      let item = this.customerSubClassifyOption.find(
        (val) => val.dictValue == this.infoData.customerSubClassify,
      );
      item = item || this.customerSubClassifyOption[0];
      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 &&
            this.infoData.isClose != 2 &&
            this.infoData.allowFollowUp
          ) {
            // response.data.customerClue.customerClueItemList[0].customerClueInfoId = this.id;
            this.taskGather = response.data.customerClue.customerClueItemList;
          }
          this.getCustomerClassify();
          // 当前客资归属人不是当前登录人和不是大区主管
          let deptIds = JSON.parse(localStorage.getItem('deptIds'));
          // regionUser：true-是大区主管  false-不是大区主管
          if (deptIds.indexOf(this.infoData.deptId) == -1 && !response.data.regionUser) {
            this.$dialog
              .confirm({
                title: '提示',
                message: '该渠道投诉已经被转移给其他人',
                showCancelButton: false,
              })
              .then(() => {
                window.location.replace(window.location.origin + this.locationOrigin + '/clew');
              });
          }
        } 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) {
            if (this.$route.query.token != undefined) {
              window.location.replace(window.location.origin + this.locationOrigin + '/clew');
            } else {
              store.dispatch('setRefreshClewPage', true);
              // 返回上一页不会刷新页面
              this.$router.go(-1);
              // this.$router.replace({ path: '/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++) {
            // 选中的题目Y:选中，N:未选中
            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].isMust == 0) {
          // 输入框
          if (optionList[i].answerType == 'wb' || optionList[i].answerType == 'sz') {
            if (!optionList[i].answerValue) {
              // 必填类型
              this.requiredFlag = false;
              this.requiredMessage = optionList[i].remark;
              return;
            } else {
              // 条件校验
              if (optionList[i].minTextLength) {
                // 输入内容长度校验
                if (optionList[i].answerValue.length < optionList[i].minTextLength) {
                  this.requiredFlag = false;
                  this.requiredMessage = optionList[i].remark;
                  return;
                }
              }
            }
          } else if (optionList[i].answerType == 'zp') {
            // 照片
            if (!optionList[i].fileInfoList || !optionList[i].fileInfoList.length) {
              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.remark;
      this.customerClassify = value.dictValue;
      this.showPicker1 = false;
      this.getCustomerSubClassify(this.customerClassify);
    },
    onConfirm2(value) {
      this.customerSubClassifyValue = value.dictLabel;
      this.customerSubClassify = value.dictValue;
      this.showPicker2 = false;
    },
    onstopVisit() {
      this.deptCode = '';
      this.regionList = [];
      this.deptList = [];
      this.companyName = '请选择公司';
      this.companyCode = '';
      this.regionName = '请选择大区';
      this.regionCode = '';
      this.deptName = '请选择销售部';
      this.show = true;
    },
    confirm(action, done) {
      if (action === 'confirm') {
        if (this.deptCode != '') {
          updateCustomerClueDept({
            customerClueInfoId: this.$route.query.id,
            deptId: this.deptCode,
          }).then((require) => {
            if (require.code == 200) {
              this.$toast.success('转发成功');
              this.show = false;
              if (this.$route.query.token != undefined) {
                window.location.replace(window.location.origin + this.locationOrigin + '/clew');
              } else {
                store.dispatch('setRefreshClewPage', true);
                // 返回上一页不会刷新页面
                this.$router.go(-1);
              }
              return done(true);
            } else {
              this.$toast(res.msg);
            }
          });
        } else {
          this.$toast('请选择要转发销售部');
          return done(false);
        }
      } else {
        return done(true);
        this.show = false;
      }
    },
    onregionConfirm(val) {
      this.RegionShow = false;
      this.companyName = val.deptName;
      this.companyCode = val.deptId;
      this.regionName = '请选择大区';
      this.regionCode = '';
      this.deptName = '请选择销售部';
      this.deptCode = '';
      this.getDeptInfo('dept', 1);
    },
    onSalesRegionConfirm(val) {
      this.SalesRegionShow = false;
      this.regionName = val.deptName;
      this.regionCode = val.deptId;
      if (val.deptId != '') {
        this.getDeptInfo('dept', 2);
      }
      this.deptName = '全部销售部';
      this.deptCode = '';
    },
    onSalesDepartmentConfirm(val) {
      this.SalesDepartmentShow = false;
      this.deptName = val.deptName;
      if (val.deptId != '') {
        this.deptCode = val.deptId;
        this.getDeptInfo('user');
      }
      this.userName = '全部业务员';
      this.userCode = '';
    },
    getDeptInfo(type, grade) {
      this.deptForm.type = type;
      if (grade == '1') {
        this.deptForm.parentId = this.companyCode;
      } else if (grade == '2') {
        this.deptForm.parentId = this.regionCode;
      } else {
        this.deptForm.type = '';
        this.deptForm.parentId = '';
      }
      getDeptInfo(this.deptForm).then((res) => {
        res.data.forEach((item) => {
          delete item.children;
        });
        if (grade == '1') {
          this.regionList = res.data;
        } else if (grade == '2') {
          this.deptList = res.data;
        } else {
          this.companyList = res.data;
        }
      });
    },
    regionClick() {
      this.RegionShow = true;
    },
    SalesRegionClick(val) {
      this.SalesRegionShow = true;
    },
    SalesDepartmentClick() {
      this.SalesDepartmentShow = true;
    },
    onClickLeft() {
      // this.$router.go(-1);
      this.$router.replace({
        path: '/clew',
      });
    },
  },
};
</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;
    padding-bottom: 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 !important;
    .van-cell__title {
      color: #000 !important;
    }
  }
  .complaintType {
    .typeItem {
      .van-cell__title {
        padding: 3px;
      }
      .van-field__value {
        padding: 3px;
        padding-left: 5px;
        border: 1px solid #ccc;
        .van-field__control {
          color: #626262;
        }
      }
    }
  }
}
</style>
