<!-- 商机-列表 -->
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商机名称" prop="boName">
        <el-input
          v-model="queryParams.boName"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商机负责人" prop="principalName">
        <el-input
          v-model="queryParams.principalName"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商机类型" prop="boType">
        <el-select
          v-model="queryParams.boType"
          @change="boTypeChange"
          clearable
        >
          <el-option
            v-for="dict in dict.type.mk_bo_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商机阶段" prop="boStage">
        <el-select v-model="queryParams.boStage" clearable>
          <el-option
            v-for="item in mk_bo_stage"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商机状态" prop="boState" clearable>
        <el-select v-model="queryParams.boState" clearable>
          <el-option
            v-for="dict in dict.type.mk_bo_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商机来源" prop="boSource">
        <el-select v-model="queryParams.boSource" clearable>
          <el-option
            v-for="dict in dict.type.mk_bo_source"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="赢单状态" prop="winningState">
        <el-select v-model="queryParams.winningState" placeholder="请输入赢单状态" clearable>
          <el-option
            v-for="dict in dict.type.mk_bo_winstate"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="basicList"
      @selection-change="handleSelectionChange"
      @cell-dblclick="enterDetails"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column
        label="编号"
        align="center"
        prop="boCode"
      />
      <el-table-column label="商机名称" align="center" prop="boName" />
      <el-table-column label="商机类型" align="center" prop="boType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mk_bo_type" :value="scope.row.boType" />
        </template>
      </el-table-column>
      <el-table-column label="商机状态" align="center" prop="boState">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.mk_bo_state"
            :value="scope.row.boState"
          />
        </template>
      </el-table-column>
      <el-table-column label="商机来源" align="center" prop="boSource">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.mk_bo_source"
            :value="scope.row.boSource"
          />
        </template>
      </el-table-column>
      <el-table-column label="商机阶段" align="center" prop="boStageName" />
      <el-table-column label="客户名称" align="center" prop="customerName" />
      <el-table-column
        label="预估值(万元)"
        align="center"
        prop="hosDiscreetValue"
      />
      <el-table-column label="赢单率" align="center" prop="winningRate" />
      <el-table-column label="赢单率状态" align="center" prop="winningState">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.mk_bo_winstate"
            :value="scope.row.winningState"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="销售区域"
        align="center"
        prop="marketingAreaName"
      />
      <el-table-column
        label="销售组织"
        align="center"
        prop="marketingOrganizingName"
      />
      <el-table-column label="部门" align="center" prop="deptName" />
      <el-table-column label="商机负责人" align="center" prop="principalName" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column
        label="操作"
        fixed="right"
        align="center"
        class-name="small-padding fixed-width"
        width="250"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="enterDetails(scope.row)"
            >进入详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleBrowse(scope.row)"
            >查看</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商机基础信息对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        :disabled="
          this.form.winningState > 0 || this.operatingState == 'Browse'
        "
      >
        <el-divider content-position="left">
          <dev style="width: 50px; height: 40px; font-size: 18px">基本信息</dev>
        </el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="商机名称" prop="boName">
              <el-input
                v-model="form.boName"
                placeholder="商机名称自动生成"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商机来源" prop="boSource">
              <el-select v-model="form.boSource">
                <el-option
                  v-for="dict in dict.type.mk_bo_source"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="推荐人"
              prop="referrerName"
              v-show="form.boSource == '2'"
              :rules="
                form.boSource == '2' ? rules.referrer : [{ require: false }]
              "
            >
              <el-input v-model="form.referrerName">
                <el-button
                  slot="append"
                  icon="el-icon-more"
                  @click="refereStaff"
                ></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="商机类型" prop="boType">
              <el-select
                v-model="form.boType"
                :disabled="this.operatingState == 'Update'"
              >
                <el-option
                  v-for="dict in dict.type.mk_bo_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称" prop="customerName">
              <el-input
                v-model="form.customerName"
                :disabled="this.operatingState == 'Update'"
              >
                <el-button
                  slot="append"
                  icon="el-icon-more"
                  @click="refereCustomer"
                  :disabled="this.operatingState == 'Update'"
                ></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="totalRevenue" prop="totalHosRevenue">
              <el-select
                v-model="form.totalHosRevenue"
                @change="totalHosRevenueChange"
              >
                <el-option
                  v-for="dict in dict.type.mk_bo_total_revenue"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item
              :label="estimate"
              prop="hosDiscreetValue"
            >
              <el-input-number
                type="number"
                :controls="false"
                v-model="form.hosDiscreetValue"
                :precision="2"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="商机内容" prop="boContent">
              <el-input
                type="textarea"
                maxlength="900"
                rows="2"
                autosize
                v-model="form.boContent"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">
          <dev style="width: 50px; height: 40px; font-size: 18px">其它信息</dev>
        </el-divider>
        <el-row>
          <el-col :span="6">
            <el-form-item label="销售区域" prop="marketingAreaName">
              <el-input
                v-model="form.marketingAreaName"
                placeholder="请输入销售区域"
              >
                <el-button
                  slot="append"
                  icon="el-icon-more"
                  @click="refereSaleaea"
                ></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售组织" prop="marketingOrganizingName">
              <el-input v-model="form.marketingOrganizingName" :disabled="true">
                <!-- <el-button slot="append" icon="el-icon-more" @click="refereOrg"></el-button> -->
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门" prop="deptName">
              <el-input v-model="form.deptName" :disabled="true">
                <!-- <el-button slot="append" icon="el-icon-more" @click="refereDept"></el-button> -->
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商机负责人" prop="principalName">
              <el-input v-model="form.principalName" :disabled="true">
                <!-- <el-button slot="append" icon="el-icon-more" @click="refereStaff"></el-button> -->
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitForm"
          v-if="this.operatingState != 'Browse'"
          :disabled="submitButtonEditStatus"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 客户参照 -->
    <CustomerRef
      ref="customerSelect"
      @doSubmit="customerSelectionsToInput"
      :single="true"
    />
    <!-- 销售区域参照 -->
    <SaleaeaRef
      ref="saleaeaSelect"
      @doSubmit="saleaeaSelectionsToInput"
      :single="true"
    />
    <!-- 组织参照 -->
    <OrgRef ref="orgSelect" @doSubmit="orgSelectionsToInput" :single="true" />
    <!-- 部门参照 -->
    <DeptRef
      ref="deptSelect"
      @doSubmit="deptSelectionsToInput"
      :single="true"
    />
    <!-- 员工参照 -->
    <StaffRef
      ref="staffSelect"
      @doSubmit="staffSelectionsToInput"
      :single="true"
    />
  </div>
</template>

<script>
import {
  listBasic,
  getBasic,
  addBasic,
  updateBasic,
  delBasic,
} from "@/api/business/spd/bo/basic";
import CustomerRef from "@/views/business/spd/bo/refer/customer/index.vue";
import SaleaeaRef from "@/views/business/spd/bo/refer/saleaea/index.vue";
import OrgRef from "@/views/business/spd/bo/refer/org/index.vue";
import DeptRef from "@/views/business/spd/bo/refer/dept/index.vue";
import StaffRef from "@/views/business/spd/bo/refer/staff/index.vue";
import { getBoNodeListByType } from "@/api/business/spd/bo/boNode";

export default {
  name: "Basic",
  dicts: [
    "mk_bo_type",
    "mk_bo_state",
    "mk_bo_source",
    "mk_bo_total_revenue",
    "mk_bo_winstate",
  ],
  components: {
    CustomerRef,
    SaleaeaRef,
    OrgRef,
    DeptRef,
    StaffRef,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商机基础信息表格数据
      basicList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //当前操作状态
      operatingState: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        boCode: null,
        boSource: null,
        boState: null,
        boStage: null,
        boName: null,
        referrer: null,
        referrerName: null,
        boType: null,
        customerName: null,
        totalHosRevenue: null,
        hosDiscreetValue: null,
        boContent: null,
        marketingArea: null,
        marketingAreaName: null,
        marketingOrganizing: null,
        marketingOrganizingName: null,
        marketingArea: null,
        dept: null,
        deptName: null,
        principal: null,
        principalName: null,
        delFlag: null,
        tenantId: null,
        revision: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      },
      // 表单参数
      form: {
        referrer: null,
        referrerName: null,
      },
      //表单校验
      rules: {
        boSource: [
          { required: true, message: "商机来源不能为空", trigger: "blur" },
        ],
        referrerName: [
          { required: true, message: "推荐人不能为空", trigger: "blur" },
        ],
        boType: [
          { required: true, message: "商机类型不能为空", trigger: "blur" },
        ],
        customerName: [
          { required: true, message: "客户名称不能为空", trigger: "blur" },
        ],
        totalHosRevenue: [
          { required: true, message: "医院营收总额不能为空", trigger: "blur" },
        ],
        hosDiscreetValue: [
          {
            required: true,
            message: "医院耗材预估值不能为空",
            trigger: "blur",
          },
        ],
        boContent: [
          { required: true, message: "商机内容不能为空", trigger: "blur" },
        ],
      },
      //阶段列表
      mk_bo_stage: [],
      // 查询日期范围
      dateRange: [],
      //确定按钮是否可点
      submitButtonEditStatus:false,
      //营收总额
      totalRevenue:"***营收总额",
      //预估额
      estimate:"***预估额（万元）",
    };
  },
  watch: {
    'form.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 对象的属性值的变化
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询商机基础信息列表 */
    getList() {
      this.loading = true;
      listBasic(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.basicList = response.rows;
          //对商机名称进行加*
          console.log(this.basicList);
          for (var i = 0; i < this.basicList.length; i++) {
            var arr = this.basicList[i].boName.split("-");
            this.basicList[i].boName =
              arr[0] +
              "-" +
              arr[1].substring(0, 2) +
              "******" +
              arr[1].substring(arr[1].length - 2, arr[1].length) +
              "-" +
              arr[2];

            var customerName = this.basicList[i].customerName;
            this.basicList[i].customerName =
              customerName.substring(0, 2) +
              "******" +
              customerName.substring(
                customerName.length - 2,
                customerName.length
              );
          }
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        boCode: null,
        boSource: null,
        boState: null,
        boStage: null,
        boName: null,
        referrer: null,
        referrerName: null,
        boType: null,
        customerName: null,
        totalHosRevenue: null,
        hosDiscreetValue: null,
        boContent: null,
        marketingArea: null,
        marketingAreaName: null,
        marketingOrganizing: null,
        marketingOrganizingName: null,
        marketingArea: null,
        dept: null,
        deptName: null,
        principal: null,
        principalName: null,
        delFlag: null,
        tenantId: null,
        revision: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.operatingState = "Insert";
      const { id, orgId, deptId, nickName, deptName, orgName } =
        this.$store.state.user;
      this.form.principal = id;
      this.form.principalName = nickName;
      this.form.dept = deptId;
      this.form.deptName = deptName;
      this.form.marketingOrganizing = orgId;
      this.form.marketingOrganizingName = orgName;
      this.title = "添加商机基础信息";
    },
    /** 进入详情按钮操作 */
    enterDetails(row) {
      console.log("列数据:", row);
      this.$router.push(`/basic/spd/bo/basic/details/${row.id}`);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getBasic(id).then((response) => {
        this.form = { ...this.form, ...response.data };
        this.open = true;
        this.operatingState = "Update";
        this.title = "修改商机基础信息";
      });
    },
    /** 查看按钮操作 */
    handleBrowse(row) {
      this.reset();
      const id = row.id || this.ids;
      getBasic(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.operatingState = "Browse";
        this.title = "基础信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.submitButtonEditStatus = true;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateBasic(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.submitButtonEditStatus = false;
            });
          } else {
            addBasic(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.submitButtonEditStatus = false;
            });
          }
        }else{
          this.submitButtonEditStatus = false;
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除商机基础信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBasic(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/basic/export",
        {
          ...this.queryParams,
        },
        `basic_${new Date().getTime()}.xlsx`
      );
    },
    //选择医院营收总额后
    totalHosRevenueChange(value) {
      switch (value) {
        //5000万以下
        case "0":
          this.form.hosDiscreetValue = 5000 * 0.2;
          break;
        //5000万-1亿
        case "1":
          this.form.hosDiscreetValue = 10000 * 0.2;
          break;
        //1亿-2亿
        case "2":
          this.form.hosDiscreetValue = 20000 * 0.2;
          break;
        //2亿-5亿
        case "3":
          this.form.hosDiscreetValue = 50000 * 0.2;
          break;
        //5亿-10亿
        case "4":
          this.form.hosDiscreetValue = 100000 * 0.2;
          break;
        //10亿以上
        case "5":
          this.form.hosDiscreetValue = 100000 * 0.2;
          break;
      }
    },
    //查询参数商机类型改变后
    boTypeChange(boType) {
      if (boType) {
        getBoNodeListByType(boType).then((response) => {
          this.mk_bo_stage = response.rows;
        });
      } else {
        this.mk_bo_stage = [];
      }
    },
    // 触发客户参照列表
    refereCustomer() {
      this.$refs.customerSelect.init();
    },
    //客户参照列表选择后
    customerSelectionsToInput(selections) {
      this.form.customer = selections[0].id;
      this.form.customerName = selections[0].name;
    },
    // 触发销售区域参照列表
    refereSaleaea() {
      this.$refs.saleaeaSelect.init();
    },
    //销售区域参照列表选择后
    saleaeaSelectionsToInput(selections) {
      this.form.marketingArea = selections[0].id;
      this.form.marketingAreaName = selections[0].name;
    },
    // 触发组织参照列表
    refereOrg() {
      this.$refs.orgSelect.init();
    },
    //组织参照列表选择后
    orgSelectionsToInput(selections) {
      this.form.marketingOrganizing = selections[0].deptId;
      this.form.marketingOrganizingName = selections[0].deptName;
    },
    // 触发部门参照列表
    refereDept() {
      this.$refs.deptSelect.init();
    },
    //部门参照列表选择后
    deptSelectionsToInput(selections) {
      this.form.dept = selections[0].deptId;
      this.form.deptName = selections[0].deptName;
    },
    // 触发员工参照列表
    refereStaff() {
      this.$refs.staffSelect.init();
    },
    //员工参照列表选择后
    staffSelectionsToInput(selections) {
      this.form.referrer = selections[0].userId;
      this.form.referrerName = selections[0].nickName;
      console.log("this.form", this.form);
    },
  },
};
</script>
