<!-- 商机-详情 -->
<template>
  <div class="md-content" v-loading="loading">
    <!-- 头部信息 -->
    <div slot="header" class="clearfix">
      <span style="width: 200px; height: 60px; font-size: 18px"  v-show="!showCustomer">
        商机详情&nbsp;{{ form.basic.boCode }}&nbsp;{{ form.basic.boName.split('-')[0] + '-' + form.basic.boName.split('-')[1].substring(0, 2) + '******' +
                  form.basic.boName.split('-')[1].substring(form.basic.boName.split('-')[1].length -
                    2, form.basic.boName.split('-')[1].length) + '-' + form.basic.boName.split('-')[2] }}
      </span>
      <span style="width: 200px; height: 60px; font-size: 18px" v-show="showCustomer">
        商机详情&nbsp;{{ form.basic.boCode }}&nbsp;{{ form.basic.boName }}
      </span>
      <el-button size="mini" type="text" icon="el-icon-view" @click="customerButton" />
      <div style="float: right; padding: 3px 0; display:flex;justify-content:space-between" type="text">
        <el-button size="mini" plain @click="handleBack">返回</el-button>
        <el-button type="info" plain size="mini" @click="handleWinningState('1', '关闭')"
          v-if="(showClose && this.form.basic.winningState == 0) && '0-2'.includes(boAuthority.post)">关闭</el-button>
        <el-button type="info" plain size="mini" @click="handleWinningState('2', '丢单')"
          v-if="(showLose && this.form.basic.winningState == 0) && '0'.includes(boAuthority.post)">丢单</el-button>
        <el-button type="info" plain size="mini" @click="handleWinningState('3', '赢单')"
          v-if="(showWin && this.form.basic.winningState == 0) && '0'.includes(boAuthority.post)">赢单</el-button>
        <el-button type="info" plain size="mini" @click="allocation()"
          v-if="this.form.basic.winningState == 0 && form.basic.principal == $store.state.user.name">分配</el-button>
      </div>
    </div>
    <!-- 基本信息 -->
    <el-divider content-position="left">
      <dev style="width: 50px; height: 40px; font-size: 18px">基本信息</dev>
    </el-divider>
    <el-descriptions :column="4">
      <el-descriptions-item label="商机来源">
        <div v-for="dict in dict.type.mk_bo_source" v-if="form.basic.boSource == dict.value">
          {{ dict.label }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item label="商机类型">
        <div v-for="dict in dict.type.mk_bo_type" v-if="form.basic.boType == dict.value">
          {{ dict.label }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item label="客户">
        <dev v-show="!showCustomer">
          {{ form.basic.customerName.substring(0, 2) + '******' +
            form.basic.customerName.substring(form.basic.customerName.length - 2, form.basic.customerName.length) }}
        </dev>
        <dev v-show="showCustomer">
          {{ form.basic.customerName }}
        </dev>
        <el-button size="mini" type="text" icon="el-icon-view" @click="customerButton" />
      </el-descriptions-item>
      <el-descriptions-item :label="totalRevenue">
        <div v-for="dict in dict.type.mk_bo_total_revenue" v-if="form.basic.totalHosRevenue == dict.value">
          {{ dict.label }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item :label="estimate">
        {{ form.basic.hosDiscreetValue }}
      </el-descriptions-item>
      <el-descriptions-item label="赢单率">
        {{ form.basic.winningRate }}
      </el-descriptions-item>
      <el-descriptions-item label="赢丢单状态">
        <div v-for="dict in dict.type.mk_bo_winstate" v-if="form.basic.winningState == dict.value">
          {{ dict.label }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item label="最近跟进">
        {{form.basic.recentlyFollowup ? form.basic.recentlyFollowup : "暂无跟进"}}
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions :column="1">
      <el-descriptions-item label="商机内容">
        {{ form.basic.boContent }}
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions :column="4" v-if="form.basic.winningState != '0'">
      <el-descriptions-item :label="winningStateTitle + '原因'">
        {{ form.basic.winningStateCause }}
      </el-descriptions-item>
      <el-descriptions-item :label="winningStateTitle + '备注'">
        {{ form.basic.winningStateRemark }}
      </el-descriptions-item>
      <el-descriptions-item :label="winningStateTitle + '日期'">
        {{new Date(form.basic.winningStateDate).Format("yyyy-MM-dd")}}
      </el-descriptions-item>
      <el-descriptions-item :label="winningStateTitle + '金额'">
        {{ form.basic.winningStateMoney }}
      </el-descriptions-item>
    </el-descriptions>
    <!-- 主多页签 -->
    <el-tabs v-model="masterTabs" @tab-click="tabsSwitch">
      <!-- 项目流程页签 -->
      <el-tab-pane label="项目流程" name="first">
        <Process :key="timer" :form="form.basic" :boAuthority="boAuthority" :boStage="boStage" :dict="dict"
          @reload="reload" />
      </el-tab-pane>
      <!-- 跟进记录 -->
      <el-tab-pane label="跟进记录" name="second">
        <BehaviorList :bo="this.form.basic" :boAuthority="boAuthority"
          v-if="masterTabs == 'second'" />
      </el-tab-pane>
      <!-- 联系人页签 -->
      <el-tab-pane label="商机联系人" name="third">
        <ContactList :source="'BoDetails'" :bo="this.form.basic" :boAuthority="this.boAuthority"
          v-if="masterTabs == 'third'" />
      </el-tab-pane>
      <!-- 商机任务页签 -->
      <el-tab-pane label="商机任务" name="fourth">
        <TaskList :source="'BoDetails'" :bo="this.form.basic" :boAuthority="this.boAuthority"
          v-if="masterTabs == 'fourth'" />
      </el-tab-pane>
      <!-- 附件页签 -->
      <el-tab-pane label="附件信息" name="five">
        <AccessoryList :source="'BoDetails'" :bo="this.form.basic" :boAuthority="this.boAuthority"
          v-if="masterTabs == 'five'" />
      </el-tab-pane>
      <!-- 模板文件页签 -->
      <el-tab-pane label="模板文件下载" name="six">
        <FileTemplate :botype="form.basic.boType" v-if="masterTabs == 'six'" />
      </el-tab-pane>
    </el-tabs>
    <!-- 其它信息 -->
    <el-divider content-position="left">
      <dev style="width: 50px; height: 40px; font-size: 18px">其它信息</dev>
    </el-divider>
    <el-descriptions :column="4">
      <el-descriptions-item label="销售组织">
        {{ form.basic.marketingOrganizingName }}
      </el-descriptions-item>
      <el-descriptions-item label="销售区域">
        {{ form.basic.marketingAreaName }}
      </el-descriptions-item>
      <el-descriptions-item label="部门">
        {{ form.basic.deptName }}
      </el-descriptions-item>
      <el-descriptions-item label="商机负责人">
        {{ form.basic.principalName }}
      </el-descriptions-item>
      <el-descriptions-item label="创建人">
        {{ form.basic.createByName }}
      </el-descriptions-item>
      <el-descriptions-item label="创建时间">
        {{ form.basic.createTime }}
      </el-descriptions-item>
    </el-descriptions>
    <!-- 赢单状态弹窗 -->
    <el-dialog :title="winningStateTitle" :visible.sync="winningStateOpen" width="500px" append-to-body>
      <el-form ref="wsform" :model="winningStateData" :rules="winningStateDataRules" label-width="140px">
        <!-- 赢单 -->
        <el-form-item label="赢单日期" prop="winningStateDate" v-if="this.winningStateData.winningState == '3'">
          <el-date-picker clearable v-model="winningStateData.winningStateDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择赢单日期" style="width:220px">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="赢单金额（万元）" prop="winningStateMoney" v-if="this.winningStateData.winningState == '3'">
          <el-input type="number" v-model="winningStateData.winningStateMoney" style="width:220px" placeholder="赢单金额" />
        </el-form-item>
        <el-form-item label="赢单原因" prop="winningStateCause" v-if="this.winningStateData.winningState == '3'">
          <el-select v-model="winningStateData.winningStateCause" placeholder="请输入">
            <el-option v-for="dict in dict.type.mk_bo_wincause" :key="dict.value" :label="dict.label"
              :value="dict.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="赢单备注" prop="winningStateRemark" v-if="this.winningStateData.winningState == '3'">
          <el-input v-model="winningStateData.winningStateRemark" style="width:220px" placeholder="请输入赢单备注" />
        </el-form-item>
        <!-- 丢单 -->
        <el-form-item label="丢单日期" prop="winningStateDate" v-if="this.winningStateData.winningState == '2'">
          <el-date-picker clearable v-model="winningStateData.winningStateDate" type="date" value-format="yyyy-MM-dd"
            placeholder="丢单日期" style="width:220px">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="丢单金额（万元）" prop="winningStateMoney" v-if="this.winningStateData.winningState == '2'">
          <el-input type="number" v-model="winningStateData.winningStateMoney" style="width:220px" placeholder="丢单金额" />
        </el-form-item>
        <el-form-item label="丢单原因" prop="winningStateCause" v-if="this.winningStateData.winningState == '2'">
          <el-select v-model="winningStateData.winningStateCause" placeholder="请输入">
            <el-option v-for="dict in dict.type.mk_bo_losecause" :key="dict.value" :label="dict.label"
              :value="dict.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="丢单备注" prop="winningStateRemark" v-if="this.winningStateData.winningState == '2'">
          <el-input v-model="winningStateData.winningStateRemark" style="width:220px" placeholder="请输入丢单备注" />
        </el-form-item>
        <!-- 关闭 -->
        <el-form-item label="关闭原因" prop="winningStateCause" v-if="this.winningStateData.winningState == '1'">
          <el-input v-model="winningStateData.winningStateCause" style="width:220px" placeholder="关闭原因" />
        </el-form-item>
        <el-form-item label="关闭备注" prop="winningStateRemark" v-if="this.winningStateData.winningState == '1'">
          <el-input v-model="winningStateData.winningStateRemark" style="width:220px" placeholder="关闭备注" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitWinningStateData">确 定</el-button>
        <el-button @click="cancelWinningStateData">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配商机负责人对话框 -->
    <el-dialog title="分配商机负责人" :visible.sync="allocationPopover" width="500px" append-to-body>
      <el-form ref="afform" :model="allocationForm" :rules="allocationFormRules" label-width="140px">
        <el-form-item label="新负责人" prop="allocationStaff">
          <dr-popover-select v-model="allocationForm.allocationStaffName" title="员工" type="CONTACTS_PARAM" :dataMapping="{
            allocationStaff: 'code',
            allocationStaffName: 'name',
          }" :source.sync="allocationForm"></dr-popover-select>
        </el-form-item>
        <el-form-item label="是否将您作为参与人" prop="isParticipant">
          <el-radio v-model="allocationForm.isParticipant" :label='true'>是</el-radio>
          <el-radio v-model="allocationForm.isParticipant" :label='false'>否</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitAllocationForm">确 定</el-button>
        <el-button @click="cancelAllocation">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getBasic,
  updateWinningState,
  allocationParticipant,
} from "@/api/business/spd/bo/basic";
import { getBoNodeListByType } from "@/api/business/spd/bo/boNode";
import { getPsnPost } from "@/api/business/spd/bo/authority";
import TaskList from "./botaskList.vue";
import ContactList from "./bocontactList.vue";
import AccessoryList from "../basic/accessoryList.vue";
import FileTemplate from "../filetemplate/botabs.vue";
import Process from '../basic/process.vue';
import BehaviorList from "./bobehaviorList.vue";


export default {
  //名称
  name: "BoDetails",
  //注册引入的组件
  components: {Process,BehaviorList,ContactList,TaskList,AccessoryList,FileTemplate},
  //平台枚举
  dicts: [
    "mk_bo_type",
    "mk_bo_state",
    "mk_bo_winstate",
    "mk_bo_source",
    "mk_bo_total_revenue",
    "mk_bo_wincause",
    "mk_bo_losecause",
    "mk_bo_stage",
  ],
  //数据
  data() {
    return {
      //赢单状态数据
      // 弹出层标题
      winningStateTitle: "",
      // 是否显示弹出层
      winningStateOpen: false,
      //赢单状态
      winningState: null,
      //赢单状态数据
      winningStateData: {},
      //赢单状态表单校验
      // 赢单表单校验
      winningStateDataRules: {
        winningStateCause: [
          { required: true, message: "原因不能为空", trigger: "blur" }
        ],
        winningStateDate: [
          { required: true, message: "日期不能为空", trigger: "blur" }
        ],
        winningStateMoney: [
          { required: true, message: "金额不能为空", trigger: "blur" }
        ],
      },
      masterTabs: "first",
      loading: false,
      // 基本信息
      form: {
        basic: {},
        accessory: [],
      },
      //权限数据
      boAuthority: {},
      //流程节点数据
      boStage: [],
      //关单按钮是否显示
      showClose: false,
      //赢单按钮是否显示
      showWin: false,
      //丢单按钮是否显示
      showLose: false,
      //重新加载子组件参数
      timer: "",
      //是否显示客户
      showCustomer: false,
      //分配参数
      allocationForm: {
        boId: null,
        allocationStaff: null,
        allocationStaffName: null,
        isParticipant: true,
      },
      //分配表单校验
      allocationFormRules: {
        allocationStaff: [
          { required: true, message: "新负责人不能为空", trigger: "blur" }
        ],
      },
      //分配弹窗
      allocationPopover: false,
      //营收总额
      totalRevenue: "***营收总额",
      //预估额
      estimate: "***预估额（万元）"
    };
  },
  watch: {
    'form.basic.boType': {
      handler(newVal, oldVal) {
        console.log('newVal', newVal);
        switch (newVal) {
          case '0':
            this.totalRevenue = "医院营收总额";
            this.estimate = "医院耗材预估值（万元）"
            break;
          case '1':
            this.totalRevenue = "医院营收总额";
            this.estimate = "医院耗材采集预估额（万元）"
            break;
          case '2':
            this.totalRevenue = "医院营收总额";
            this.estimate = "医院耗材预估值（万元）"
            break;
          case '3':
            this.totalRevenue = "医院营收总额";
            this.estimate = "医院设备预估额（万元）"
            break;
          case '4':
            this.totalRevenue = "医院营收总额";
            this.estimate = "军队医院设备预估额（万元）"
            break;
          case '5':
            this.totalRevenue = "项目总额";
            this.estimate = "工程预估额（万元）"
            break;
          default:
            break;
        }
      },
      immediate: true,
      deep: true // 可以深度检测到 person 对象的属性值的变化
    }
  },
  //方法
  methods: {
    // 返回
    handleBack() {
      this.$router.back()
    },
    //主多页签切换
    tabsSwitch(e) {
      switch (e.name) {
        case "second":
          //任务
          break;
        case "third":
          //联系人
          break;
        case "fourth":
          //附件
          break;
        case "five":
          //文件模板
          break;
        default:
          break;
      }
    },
    //赢单状态按钮
    handleWinningState(winningState, title) {
      this.resetWinningStateData();
      this.winningStateOpen = true;
      this.winningStateTitle = title;
      this.winningStateData.winningState = winningState;
      this.winningStateData.boId = this.form.basic.id;
      this.winningStateData.winningStateDate = new Date();
    },
    resetWinningStateData() {
      this.winningStateData = {
        boId: null,
        winningState: null,
        winningStateCause: null,
        winningStateRemark: null,
        winningStateDate: null,
        winningStateMoney: null,
      }
    },
    submitWinningStateData() {
      this.$refs["wsform"].validate(valid => {
        if (valid) {
          updateWinningState(this.winningStateData).then(response => {
            this.$modal.msgSuccess("提交成功");
            this.winningStateOpen = false;
            this.reload();
          });
        }
      });
    },
    cancelWinningStateData() {
      this.winningStateOpen = false;
      this.resetWinningStateData();
    },
    //打开分配弹窗
    allocation() {
      this.allocationPopover = true;
    },
    //提交分配表单
    submitAllocationForm() {
      // this.allocationForm.boId = parseInt(this.form.basic.id);
      // this.allocationForm.allocationStaff = parseInt(this.allocationForm.allocationStaff);
      this.allocationForm.boId = this.form.basic.id;
      this.$refs["afform"].validate(valid => {
        if (valid) {
          allocationParticipant(this.allocationForm).then(response => {
            console.log('response', response);
            this.$modal.msgSuccess("分配成功");
            this.allocationPopover = false;
            this.reload();
          });
        }
      });
    },
    //取消分配
    cancelAllocation() {
      this.allocationPopover = false;
    },
    //重新加载数据
    async reload() {
      this.loading = true;
      //加载基础数据
      let res = await getBasic(this.$route.params.id);
      this.form.basic = res.data;
      //设置应丢关单标题
      switch(this.form.basic.winningState){
        case "1" : this.winningStateTitle = "关闭";break;
        case "2" : this.winningStateTitle = "丢单";break;
        case "3" : this.winningStateTitle = "赢单";break;
      }
      //加载流程节点数据
      let bnRes = await getBoNodeListByType(this.form.basic.boType);
      this.boStage = bnRes.rows;
      console.log('this.boStage', this.boStage);
      //赢丢单按钮显示逻辑
      var auditNode = 999;
      var curNode = 0;
      var signContract = 999;
      for (var i = 0; i < this.boStage.length; i++) {
        if (this.boStage[i].code == this.form.basic.boStage) {
          curNode = i;
        }
        if (this.boStage[i].name.toString().includes('审核')) {
          auditNode = i;
        }
        if (this.boStage[i].name.toString().includes('合同')) {
          signContract = i;
        }
      }
      this.showClose = false;
      this.showLose = false;
      this.showWin = false;
      if (curNode != auditNode) {
        this.showClose = true;
      }
      if (curNode > auditNode) {
        this.showLose = true;
      }
      if (curNode >= signContract) {
        this.showWin = true;
      }
      //确定数据加载完成，子组件可以开始展示
      this.timer = new Date().getTime();
      this.loading = false;
      //加载权限数据
      getPsnPost(this.form.basic.id).then((response) => {
        this.boAuthority = response.data;
      });
    },
    //是否显示客户
    customerButton() {
      this.showCustomer = !this.showCustomer;
    },
  },
  //创建钩子
  async created() {
    this.loading = true;
    //加载基础数据
    let res = await getBasic(this.$route.params.id);
    this.form.basic = res.data;
    //设置应丢关单标题
    switch(this.form.basic.winningState){
      case "1" : this.winningStateTitle = "关闭";break;
      case "2" : this.winningStateTitle = "丢单";break;
      case "3" : this.winningStateTitle = "赢单";break;
    }
    //加载流程节点数据
    let bnRes = await getBoNodeListByType(this.form.basic.boType);
    this.boStage = bnRes.rows;
    console.log('this.boStage', this.boStage);
    //赢丢单按钮显示逻辑
    var auditNode = 999;
    var curNode = 0;
    var signContract = 999;
    for (var i = 0; i < this.boStage.length; i++) {
      if (this.boStage[i].code == this.form.basic.boStage) {
        curNode = i;
      }
      if (this.boStage[i].name.toString().includes('审核')) {
        auditNode = i;
      }
      if (this.boStage[i].name.toString().includes('合同')) {
        signContract = i;
      }
    }
    this.showClose = false;
    this.showLose = false;
    this.showWin = false;
    if (curNode != auditNode) {
      this.showClose = true;
    }
    if (curNode > auditNode) {
      this.showLose = true;
    }
    if (curNode >= signContract) {
      this.showWin = true;
    }
    //确定数据加载完成，子组件可以开始展示
    this.timer = new Date().getTime();
    this.loading = false;
    //加载权限数据
    getPsnPost(this.form.basic.id).then((response) => {
      this.boAuthority = response.data;
    });
  },
};
</script>


<style scoped>
.md-content>>>.el-form-item {
  margin-bottom: 10px;
}

.md-content>>>.el-tabs--border-card>.el-tabs__content {
  padding-bottom: 8px;
}

.md-content .md-auditInfo>>>.el-form-item {
  margin-bottom: 0px;
}

.md-main>>>.el-form-item,
.md-vice>>>.el-form-item {
  width: 100%;
  box-sizing: border-box;
}

.md-main>>>.el-form-item__label,
.md-vice>>>.el-form-item__label {
  width: 40%;
}

.md-main>>>.el-form-item__content,
.md-md-vice>>>.el-form-item__content {
  width: 60%;
}

.md-content>>>.el-form-item__label {
  font-weight: normal;
  /* text-align: left;
  width: 28%; */
  white-space: nowrap;
  /* IE6 需要定义宽度 */
  overflow: hidden;

  -o-text-overflow: ellipsis;
  /* Opera */
  text-overflow: ellipsis;
  /* IE, Safari (WebKit) */
  /* -moz-binding: url('ellipsis.xml#ellipsis'); */
  /* Firefox */
}

.md-main>>>.material-table {
  height: 100%;
}

.md-vice>>>.material-table {
  height: 140px;
  overflow-y: auto;
  overflow-x: auto;
}
</style>
