<!-- 商机-详情 -->
<template>
  <div class="md-content">
    <!-- 头部信息 -->
    <el-row type="flex" class="row-bg" justify="space-around">
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <el-button type="info" plain icon="el-icon-back" size="small" @click="handleBack">返回</el-button>
        </div>
      </el-col>
      <el-col :span="16">
        <div class="grid-content bg-purple-light">
          <el-descriptions :colon="false" :size="medium">
            <el-descriptions-item>
              <dev style="width: 200px; height: 60px; font-size: 18px" v-show="!showCustomer">
                {{ 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] }}</dev>
              <dev style="width: 200px; height: 60px; font-size: 18px" v-show="showCustomer">{{ form.basic.boName }}</dev>
              <el-button size="mini" type="text" icon="el-icon-view" @click="customerButton" />
            </el-descriptions-item>
            <el-descriptions-item label="商机状态:" style="margin-left:27px">
              <div v-for="dict in dict.type.mk_bo_state" v-if="form.basic.boState == dict.value">
                <div>{{ dict.label }}</div>
              </div>
            </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>
        </div>
      </el-col>
      <el-col :span="6">
        <el-button type="info" plain icon="el-icon-delete-solid" size="small" @click="handleWinningState('1', '关闭')"
          v-if="(showClose && this.form.basic.winningState == 0) && this.boAuthority.boAuthority.boClose">关闭</el-button>
        <el-button type="info" plain icon="el-icon-close" size="small" @click="handleWinningState('2', '丢单')"
          v-if="(showLose && this.form.basic.winningState == 0) && this.boAuthority.boAuthority.boLose">丢单</el-button>
        <el-button type="info" plain icon="el-icon-check" size="small" @click="handleWinningState('3', '赢单')"
          v-if="(showWin && this.form.basic.winningState == 0) && this.boAuthority.boAuthority.boWin">赢单</el-button>
        <el-button type="info" plain icon="el-icon-user" size="small" @click="allocation()"
          v-if="this.boAuthority.post == 0 && this.form.basic.winningState == 0">分配</el-button>
      </el-col>
    </el-row>
    <!-- 主多页签 -->
    <el-tabs v-model="masterTabs" @tab-click="tabsSwitch">
      <!-- 基本信息页签 -->
      <el-tab-pane label="基本信息" name="first">
        <el-divider content-position="left" style="font-size: 30px">
          <dev style="width: 50px; height: 40px; font-size: 18px">项目流程</dev>
        </el-divider>
        <Process :key="timer" :form="form.basic" :boAuthority="boAuthority" :boStage="boStage" :dict="dict"
          @reload="reload" />
        <!-- 基本信息 -->
        <el-divider content-position="left">
          <dev style="width: 50px; height: 40px; font-size: 18px">基本信息</dev>
        </el-divider>
        <el-descriptions>
          <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="商机内容">
            {{ form.basic.boContent }}
          </el-descriptions-item>
        </el-descriptions>
        <!-- 其它信息 -->
        <el-divider content-position="left">
          <dev style="width: 50px; height: 40px; font-size: 18px">其它信息</dev>
        </el-divider>
        <el-descriptions>
          <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.creatorName }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ form.basic.createTime }}
          </el-descriptions-item>
        </el-descriptions>
      </el-tab-pane>
      <!-- 商机任务页签 -->
      <el-tab-pane label="商机任务" name="second">
        <TaskList :source="'BoDetails'" :bo="this.form.basic" :boAuthority="this.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">
        <AccessoryList :source="'BoDetails'" :bo="this.form.basic" :boAuthority="this.boAuthority"
          v-if="masterTabs == 'fourth'" />
      </el-tab-pane>
      <!-- 模板文件页签 -->
      <el-tab-pane label="模板文件下载" name="five">
        <FileTemplate :botype="form.basic.boType" v-if="masterTabs == 'five'" />
      </el-tab-pane>
    </el-tabs>

    <!-- 赢单状态弹窗 -->
    <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" class="dialog-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: 'id',
            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" class="dialog-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 "../task/taskList.vue";
import ContactList from "../contact/contactList.vue";
import AccessoryList from "../basic/accessoryList.vue";
import FileTemplate from "../filetemplate/botabs.vue";
import Process from '../basic/process.vue';


export default {
  //名称
  name: "BoDetails",
  //注册引入的组件
  components: { TaskList, ContactList, AccessoryList, FileTemplate, Process,},
  //平台枚举
  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.push("/business/spd/bo/basic");
    },
    //主多页签切换
    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;
      console.log('this.allocationForm', this.allocationForm);
      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;
    },
    //重新加载数据
    reload() {
      //加载基础数据
      getBasic(this.$route.params.id).then((response) => {
        this.form.basic = response.data;
        //加载权限数据
        getPsnPost(this.form.basic.id).then((response) => {
          this.boAuthority = response.data;
        });
        //加载流程节点数据
        getBoNodeListByType(this.form.basic.boType).then(response => {
          this.boStage = response.rows;
          //赢丢单按钮显示逻辑
          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();
        });
      });
    },
    //是否显示客户
    customerButton() {
      this.showCustomer = !this.showCustomer;
    },
  },
  //创建钩子
  created() {
    //加载基础数据
    getBasic(this.$route.params.id).then((response) => {
      this.form.basic = response.data;
      //加载权限数据
      getPsnPost(this.form.basic.id).then((response) => {
        this.boAuthority = response.data;
      });
      //加载流程节点数据
      getBoNodeListByType(this.form.basic.boType).then(response => {
        this.boStage = response.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();
      });
    });
  },
};
</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>
