<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <el-row :gutter="1" justify="space-between">
        <el-col :span="4">
          <el-form-item label="医院名称" prop="customerName">
            <el-popover-select-v2 v-model="queryParams.customerName" title="医院" valueKey="name"
              referName="MkCustomerRule" :dataMapping="{ customer: 'id', customerName: 'name'}"
              :source.sync="queryParams" placeholder="请输入医院名称" @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="有效状态" prop="effectiveState">
            <el-select v-model="queryParams.effectiveState" placeholder="" clearable>
              <el-option
                v-for="dict in dict.type.mk_bo_effectivestate"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="产线" prop="productionLineName">
            <el-popover-tree-select v-model="queryParams.productionLineName" valueKey='name' title="产线"
              referName="PRODUCTLINE" :dataMapping="{ productionLine: 'id', productionLineName: 'name'}"
              :source.sync="queryParams" placeholder="请输入产线" @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="供应商名称" prop="rivalName" label-width="120px">
            <el-popover-select-v2 v-model="queryParams.rivalName" title="供应商" valueKey="name" referName="MKRIVAL_PARAM"
              :dataMapping="{ rival: 'id', rivalName: 'name'}" :source.sync="queryParams" placeholder="请输入供应商"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="创建日期范围" prop="dateRange" label-width="120px">
            <el-date-picker v-model="queryParams.dateRange" type="daterange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <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-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8" style="float: right">
      <!-- <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="primary" plain icon="el-icon-download" size="mini" @click="handleDownload">模板下载</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-upload ref="upload" action="" :http-request="handleUpload">
          <el-button size="mini" type="primary">导入</el-button>
        </el-upload>
      </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> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="gatherList" @selection-change="handleSelectionChange" size="mini" >
      <el-table-column type="selection" align="center" />
      <el-table-column label="序号" type="index" align="center" />
      <el-table-column label="有效状态" width="150" align="center" prop="boState">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.mk_bo_effectivestate"
            :value="scope.row.effectiveState"
          />
        </template>
      </el-table-column>
      <el-table-column label="医院名称" align="center" prop="customerName" width="220" />
      <el-table-column label="产线" align="center" prop="productionLineName" width="150" />
      <el-table-column label="供应商" align="center" prop="rivalName" width="220" />
      <el-table-column label="医院营收总额/年（万元）" align="center" prop="customerBulk" width="160" />
      <el-table-column label="供应商体量/年（万元）" align="center" prop="rivalBulk" width="160" />
      <el-table-column label="耗材体量/年（万元）" align="center" prop="consumableBulk" width="160" />
      <el-table-column label="科室" align="center" prop="sectionName" width="90" />
      <el-table-column label="科室关键人姓名" align="center" prop="sectionKeyPsnname" width="90" />
      <el-table-column label="科室关键人联系电话" align="center" prop="sectionKeyPsnphone" width="120" />
      <el-table-column label="院级关键人姓名" align="center" prop="hospitalKeyPsnname" width="90" />
      <el-table-column label="院级关键人联系电话" align="center" prop="hospitalKeyPsnphone" width="120" />
      <el-table-column label="供应商关键人姓名" align="center" prop="rivalKeyPsnname" width="100" />
      <el-table-column label="供应商关键人联系电话" align="center" prop="rivalKeyPsnphone" width="130" />
      <el-table-column label="开发思路（营销策略）" align="center" prop="idea" min-width="220" show-overflow-tooltip />
      <el-table-column label="机会点/困难点所需资源" align="center" prop="chance" min-width="220" show-overflow-tooltip />
      <el-table-column label="备注" align="center" prop="remark" min-width="220" show-overflow-tooltip />
      <el-table-column label="创建人" align="center" prop="createByName" width="180" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
      <el-table-column label="最后修改人" align="center" prop="updateByName" width="180" />
      <el-table-column label="最后修改时间" align="center" prop="updateTime" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180px" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleSee(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" @click="effectiveBtn(scope.row)">有效</el-button>
          <el-button size="mini" type="text" @click="loseEffectiveBtn(scope.row)">失效</el-button>
          <el-button size="mini" type="text" @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="90%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :disabled="pageState == 'see'">
        <el-row>
          <el-col :span="6">
            <el-form-item label="医院名称" prop="customerName">
              <el-popover-select-v2 v-model="form.customerName" title="医院" valueKey="name" referName="MkCustomerRule"
                :dataMapping="{ customer: 'id', customerName: 'name'}" :source.sync="form" placeholder="请输入医院名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产线" prop="productionLineName">
              <el-popover-tree-select v-model="form.productionLineName" valueKey='name' title="产线"
                referName="PRODUCTLINE" :dataMapping="{ productionLine: 'id', productionLineName: 'name'}"
                :source.sync="form" placeholder="请输入产线" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商名称" prop="rivalName" label-width="100px">
              <el-popover-select-v2 v-model="form.rivalName" title="供应商" valueKey="name" referName="MKRIVAL_PARAM"
                :dataMapping="{ rival: 'id', rivalName: 'name'}" :source.sync="form" placeholder="请输入供应商名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="医院营收总额/年（万元）" prop="customerBulk" label-width="160px">
              <el-input-number v-model="form.customerBulk" :precision="2" :step="1"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商体量/年（万元）" prop="rivalBulk" label-width="160px">
              <el-input-number v-model="form.rivalBulk" :precision="2" :step="1"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="耗材体量/年（万元）" prop="consumableBulk" label-width="160px">
              <el-input-number v-model="form.consumableBulk" :precision="2" :step="1"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="科室" prop="section">
              <el-popover-select-v2 v-model="form.sectionName" title="科室" valueKey="name" referName="MkCustomersDepartmentRule"
                :dataMapping="{ section: 'id', sectionName: 'name'}" :source.sync="form" :queryParams="additionalCondition" placeholder="请选择科室" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="科室关键人姓名" prop="sectionKeyPsnname" label-width="110px">
              <el-input v-model="form.sectionKeyPsnname" placeholder="请输入科室关键人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="科室关键人联系电话" prop="sectionKeyPsnphone" label-width="140px">
              <el-input v-model="form.sectionKeyPsnphone" placeholder="请输入科室关键人联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="院级关键人姓名" prop="hospitalKeyPsnname" label-width="110px">
              <el-input v-model="form.hospitalKeyPsnname" placeholder="请输入院级关键人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="院级关键人联系电话" prop="hospitalKeyPsnphone" label-width="140px">
              <el-input v-model="form.hospitalKeyPsnphone" placeholder="请输入院级关键人联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商关键人姓名" prop="rivalKeyPsnname" label-width="140px">
              <el-input v-model="form.rivalKeyPsnname" placeholder="请输入供应商关键人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商关键人联系电话" prop="rivalKeyPsnphone" label-width="170px">
              <el-input v-model="form.rivalKeyPsnphone" placeholder="请输入供应商关键人联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="开发思路（营销策略）" prop="idea" label-width="160px">
          <el-input v-model="form.idea" placeholder="请输入开发思路（营销策略）" type="textarea" />
        </el-form-item>
        <el-form-item label="机会点/困难点所需资源" prop="chance" label-width="160px">
          <el-input v-model="form.chance" placeholder="请输入机会点/困难点所需资源" type="textarea" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="pageState == 'see'">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listGather,
    getGather,
    delGather,
    addGather,
    updateGather,
    upload,
    effective,
    loseEffective
  } from "@/api/business/spd/bo/gather";

  export default {
    name: "Gather",
    dicts: ["mk_bo_effectivestate"],
    components: {
      ElPopoverSelectV2: () =>
        import("@/components/popover-select-v2"),
      ElPopoverTreeSelect: () =>
        import("@/components/popover-tree-select/index.vue"),
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 竞争产品信息收集表格数据
        gatherList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          customer: null,
          customerName: null,
          productionLine: null,
          productionLineName: null,
          rival: null,
          rivalName: null,
          rivalBulk: null,
          consumableBulk: null,
          brand: null,
          brandPortion: null,
          cooperationStart: null,
          cooperationEnd: null,
          section: null,
          sectionName: null,
          sectionKeyPsnname: null,
          sectionKeyPsnphone: null,
          hospitalKeyPsnname: null,
          hospitalKeyPsnphone: null,
          rivalKeyPsnname: null,
          rivalKeyPsnphone: null,
          idea: null,
          chance: null,
          tenantId: null,
          revision: null,
          dateRange: null,
          staff: this.$store.state.user.id,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          customerName: [{
            required: true,
            message: '医院名称不能为空',
            trigger: 'blur'
          }],
          productionLineName: [{
            required: true,
            message: '产线不能为空',
            trigger: 'blur'
          }],
          rivalName: [{
            required: true,
            message: '供应商名称不能为空',
            trigger: 'blur'
          }],
        },
        // 页面状态
        pageState: null,
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询竞争产品信息收集列表 */
      getList() {
        this.loading = true;
        listGather(this.queryParams).then(response => {
          this.gatherList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          customer: null,
          customerName: null,
          productionLine: null,
          productionLineName: null,
          rival: null,
          rivalName: null,
          rivalBulk: null,
          consumableBulk: null,
          brand: null,
          brandPortion: null,
          cooperationStart: null,
          cooperationEnd: null,
          section: null,
          sectionName: null,
          sectionKeyPsnname: null,
          sectionKeyPsnphone: null,
          hospitalKeyPsnname: null,
          hospitalKeyPsnphone: null,
          rivalKeyPsnname: null,
          rivalKeyPsnphone: null,
          idea: null,
          chance: null,
          remark: null,
          tenantId: null,
          revision: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          delFlag: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        if (this.queryParams.dateRange != undefined && this.queryParams.dateRange != null) {
          let date = this.queryParams.dateRange[1];
          if (String(date).indexOf("00:00:00") >= 0) {
            this.queryParams.dateRange[0] = this.dateToStr(this.queryParams.dateRange[0]);
            this.queryParams.dateRange[1] = this.dateToStrEnd(this.queryParams.dateRange[1]);
          }
        }
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          customer: null,
          customerName: null,
          productionLine: null,
          productionLineName: null,
          rival: null,
          rivalName: null,
          rivalBulk: null,
          consumableBulk: null,
          brand: null,
          brandPortion: null,
          cooperationStart: null,
          cooperationEnd: null,
          section: null,
          sectionName: null,
          sectionKeyPsnname: null,
          sectionKeyPsnphone: null,
          hospitalKeyPsnname: null,
          hospitalKeyPsnphone: null,
          rivalKeyPsnname: null,
          rivalKeyPsnphone: null,
          idea: null,
          chance: null,
          tenantId: null,
          revision: null,
          dateRange: null,
          staff: this.$store.state.user.id,
          dateRange: null,
        },
        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.title = "添加项目信息收集";
        this.pageState = 'insert';
      },
      /** 模板下载按钮操作 */
      handleDownload() {
        this.download('mk/bo/gathercg/download', {}, `项目信息收集导入模板_${new Date().getTime()}.xlsx`)
      },
      /** 导入按钮操作 */
      handleUpload(file) {
        this.loading = true;
        let formData = new FormData()
        formData.append('file', file.file)
        upload(formData).then((res) => {
          console.log('res', res);
          if (res.code == '200') {
            this.resetQuery();
            if (res.msg.indexOf('导入失败') >= 0) {
              this.$message({
                duration: 5000,
                message: res.msg
              });
            } else {
              this.$message.success(res.msg);
            }
          } else {
            this.$message.error(res.msg);
          }
          this.loading = false;
        }).catch((e) => {
          this.$message.error(e.message)
        }).finally((e) => {
          this.$refs['upload'].clearFiles();
          this.loading = false;
        })
      },
      /** 查看按钮操作 */
      handleSee(row) {
        this.reset();
        const id = row.id || this.ids
        getGather(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "查看项目信息收集";
          this.pageState = 'see';
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getGather(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改项目信息收集";
          this.pageState = 'update';
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateGather(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addGather(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        if (row.id != undefined) {
          this.ids.push(row.id);
        }
        const ids = this.ids;
        this.$modal.confirm('是否确认删除？').then(function () {
          return delGather(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('mk/bo/gathercg/export', {
          ...this.queryParams
        }, '项目信息收集_' + this.dateToStrDownload(new Date()) + '.xlsx')
      },
      // 日期转字符串格式
      dateToStr(date) {
        var year = date.getFullYear(); // 年
        var month = date.getMonth(); // 月
        var day = date.getDate(); // 日
        var hours = date.getHours(); // 时
        var min = date.getMinutes(); // 分
        var second = date.getSeconds(); // 秒
        return year + "-" +
          ((month + 1) > 9 ? (month + 1) : "0" + (month + 1)) + "-" +
          (day > 9 ? day : ("0" + day)) + " " +
          (hours > 9 ? hours : ("0" + hours)) + ":" +
          (min > 9 ? min : ("0" + min)) + ":" +
          (second > 9 ? second : ("0" + second));
      },
      dateToStrEnd(date) {
        var year = date.getFullYear(); // 年
        var month = date.getMonth(); // 月
        var day = date.getDate(); // 日
        return year + "-" +
          ((month + 1) > 9 ? (month + 1) : "0" + (month + 1)) + "-" +
          (day > 9 ? day : ("0" + day)) + " " + "23:59:59"
      },
      dateToStrDownload(date) {
        var year = date.getFullYear(); // 年
        var month = date.getMonth(); // 月
        var day = date.getDate(); // 日
        var hours = date.getHours(); // 时
        var min = date.getMinutes(); // 分
        var second = date.getSeconds(); // 秒
        return year + "_" +
          ((month + 1) > 9 ? (month + 1) : "0" + (month + 1)) + "_" +
          (day > 9 ? day : ("0" + day)) + "_" +
          (hours > 9 ? hours : ("0" + hours)) + "_" +
          (min > 9 ? min : ("0" + min)) + "_" +
          (second > 9 ? second : ("0" + second));
      },
      //联系人弹窗附加查询条件
      additionalCondition(){
        return {
          parame:{
            customer: this.form.customer
          }
        }
      },
      effectiveBtn(row){
        this.$modal.loading("保存中");
        effective(row.id).then(response => {
          this.$modal.msgSuccess("设置成功");
          this.$modal.closeLoading();
          this.getList();
        });
      },
      loseEffectiveBtn(row){
        this.$modal.loading("保存中");
        loseEffective(row.id).then(response => {
          this.$modal.msgSuccess("设置成功");
          this.$modal.closeLoading();
          this.getList();
        });
      },
    }
  };

</script>
