<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" :source="'assignPage'"></assignAwaitDetail>
    <!-- 选择分配组织 -->
    <div class="assign">
      <van-form validate-first @failed="onFailed" @submit="onSubmit" :show-error="false">
        <van-field
          readonly
          clickable
          name="picker"
          :value="assignTypeValue"
          label="客资类型"
          placeholder="点击选择客资类型"
          right-icon="arrow"
          :rules="[{ required: true, message: '请选择客资类型' }]"
          @click="showPicker = true" />
        <van-field
          v-if="activaAssignTypeItem && activaAssignTypeItem.dictValue != 1"
          readonly
          clickable
          name="picker"
          :value="assignUserPostValue"
          label="分配人员岗位"
          placeholder="点击选择分配人员岗位"
          right-icon="arrow"
          :rules="[{ required: true, message: '请选择分配人员岗位' }]"
          @click="assignUserPostShow = true" />
        <van-field
          readonly
          clickable
          name="picker"
          :value="assignUserValue"
          label="分配人员"
          placeholder="点击选择分配人员"
          right-icon="arrow"
          :rules="[{ required: true, message: '请选择分配人员' }]"
          @click="assignUserShow = true" />
        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit">提交</van-button>
        </div>
      </van-form>
    </div>
    <!-- 类型选择 -->
    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        show-toolbar
        value-key="dictLabel"
        :columns="assignTypeData"
        @confirm="onConfirm"
        @cancel="showPicker = false" />
    </van-popup>
    <!-- 分配人员岗位 -->
    <van-popup v-model="assignUserPostShow" position="bottom">
      <van-picker
        show-toolbar
        value-key="postName"
        :columns="assignUserPostData"
        @confirm="onConfirmAssignUserPost"
        @cancel="assignUserPost = false" />
    </van-popup>
    <!-- 分配人员选择 -->
    <van-popup v-model="assignUserShow" position="bottom">
      <van-picker
        show-toolbar
        value-key="nickName"
        :columns="assignUserData"
        @confirm="onConfirmAssignUser"
        @cancel="assignUserShow = false" />
    </van-popup>
  </div>
</template>

<script>
import { getCustomerClueInfoById } from '@/api/clew';
import { getDictOption } from '@/api/index';
import assignAwaitDetail from './assignAwaitDetail.vue';
import {
  selectUserListByCustomerType,
  selectUserListByPostName,
  allocationCustomer,
} from '@/api/assignAwait';

export default {
  name: 'assignPage',
  components: {
    assignAwaitDetail,
  },
  data() {
    return {
      id: '',
      infoData: {},
      collectionItemList: [],
      showPicker: false,
      assignUserPostShow: false,
      assignUserShow: false,
      columns: [],
      valueKey: '',
      assignTypeData: [], //客资类型下拉选数据
      activaAssignTypeItem: null, //客资类型当前选择的数据
      assignTypeValue: '', //客资类型选中value
      assignUserPostData: [], //分配人员岗位下拉选数据
      assignUserPostItem: null, //分配人员岗位当前选择的数据
      assignUserPostValue: '', //分配人员岗位选中value
      assignUserData: [], //分配人员下拉选数据
      assignUserItem: null, //分配人员当前选择的数据
      assignUserValue: '', //分配人员选中value
      title: '',
    };
  },
  watch: {
    'activaAssignTypeItem.dictValue': {
      handler(val) {
        if (val) this.getSelectUserListByCustomerType();
      },
    },
    'assignUserPostItem.postName': {
      handler(val) {
        if (val) this.getSelectUserListByPostName();
      },
      deep: true,
    },
  },
  activated() {
    this.id = this.$route.query.id;
    this.getCustomerClueInfoById();
  },
  methods: {
    async getDictOptionFun() {
      // 获取字典（jz_customer_type）参数对应的备注值，如果选择大型装企直接返回用户表列表
      let customer = await getDictOption({}, 'jz_customer_type');
      if (customer.data && customer.data.length) {
        this.assignTypeData = customer.data;
        this.activaAssignTypeItem = this.assignTypeData[0];
        this.assignTypeValue = this.activaAssignTypeItem.dictLabel;
      } else {
        this.assignTypeData = [];
        this.activaAssignTypeItem = null;
        this.assignTypeValue = '';
      }
    },
    getSelectUserListByCustomerType() {
      let params = JSON.parse(this.activaAssignTypeItem.remark);
      selectUserListByCustomerType(params).then((res) => {
        if (res.code == 200) {
          // 如果选择大型装企直接返回用户表列表
          if (this.activaAssignTypeItem.dictValue == 1) {
            if (res.data && res.data.userList.length) {
              let userList = res.data.userList;
              if (this.assignTypeValue != '大型装企') {
                let userListFilter = userList.filter(
                  (item) => item.nickName.indexOf(this.infoData.companyName) != -1,
                );
                this.assignUserData = userListFilter || [];
              } else {
                this.assignUserData = userList;
              }
              if (this.assignUserData.length) {
                this.assignUserItem = this.assignUserData[0];
                this.assignUserValue = this.assignUserItem.nickName;
              } else {
                this.assignUserData = [];
                this.assignUserItem = null;
                this.assignUserValue = '';
              }
            } else {
              this.assignUserData = [];
              this.assignUserItem = null;
              this.assignUserValue = '';
            }
          } else {
            if (res.data && res.data.postList.length) {
              let resData = [];
              res.data.postList.forEach((val) => {
                resData.push({
                  postName: val,
                });
              });
              this.assignUserPostData = resData;
              this.assignUserPostItem = this.assignUserPostData[0];
              this.assignUserPostValue = this.assignUserPostItem.postName;
            } else {
              this.assignUserPostData = [];
              this.assignUserPostItem = null;
              this.assignUserPostValue = '';
            }
          }
        } else {
          this.$toast(res.msg);
        }
      });
    },
    getSelectUserListByPostName() {
      selectUserListByPostName({ postName: this.assignUserPostValue }).then((res) => {
        if (res.code == 200) {
          if (res.data && res.data.userList.length) {
            let userList = res.data.userList;
            if (this.assignTypeValue != '大型装企') {
              let userListFilter = userList.filter(
                (item) => item.nickName.indexOf(this.infoData.companyName) != -1,
              );
              this.assignUserData = userListFilter || [];
            } else {
              this.assignUserData = userList;
            }
            if (this.assignUserData.length) {
              this.assignUserItem = this.assignUserData[0];
              this.assignUserValue = this.assignUserItem.nickName;
            } else {
              this.assignUserData = [];
              this.assignUserItem = null;
              this.assignUserValue = '';
            }
          } else {
            this.assignUserData = [];
            this.assignUserItem = null;
            this.assignUserValue = '';
          }
        } else {
          this.$toast(res.msg);
        }
      });
    },
    getCustomerClueInfoById() {
      this.id = this.$route.query.id;
      this.collectionAnswerlisd = [];
      this.collectionItemList = [];
      getCustomerClueInfoById({ customerClueInfoId: this.id }).then((response) => {
        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.allocationStatus == 1) {
            this.$dialog
              .confirm({
                title: '提示',
                message: '该客资已经被分配',
                showCancelButton: false,
              })
              .then(() => {
                window.location.replace(
                  window.location.origin + this.locationOrigin + '/assignAwait',
                );
              });
          }
          this.getDictOptionFun();
        } else {
          this.$toast(res.msg);
        }
      });
    },
    onSubmit() {
      this.toastLoading(0, '加载中...', true);
      allocationCustomer({
        userId: this.assignUserItem.userId || '', //	string	用户ID
        customerClueInfoId: this.id, //	string	客资主键ID
        customerClassify: this.activaAssignTypeItem.dictValue || '', //	string	客资类型，（取值页面字典选择的值 jz_customer_type）
      }).then((res) => {
        this.toastLoading().clear();
        if (res.code == 200) {
          this.$toast(res.msg);
          window.location.replace(window.location.origin + this.locationOrigin + '/assignAwait');
        } else {
          this.$toast(res.msg);
        }
      });
    },
    // 校验错误返回信息
    onFailed(errorInfo) {
      console.log('failed', errorInfo);
    },
    onConfirm(value) {
      this.activaAssignTypeItem = value;
      this.assignTypeValue = this.activaAssignTypeItem.dictLabel;
      this.showPicker = false;
    },
    onConfirmAssignUserPost(value) {
      this.assignUserPostItem = value;
      this.assignUserPostValue = this.assignUserPostItem.postName;
      this.assignUserPostShow = false;
    },
    onConfirmAssignUser(value) {
      this.assignUserItem = value;
      this.assignUserValue = this.assignUserItem.nickName;
      this.assignUserShow = false;
    },
    onClickLeft() {
      this.$router.go(-1);
    },
  },
};
</script>
<style scoped lang="scss">
.assignPage {
}
</style>
<style lang="scss">
.assignPage {
  .van-field__label {
    width: 100px;
    &::before {
      content: '*';
      color: red;
    }
  }
}
</style>
