vue iview table表格 render函数 自动合并单元格

vue iview table表格 render函数 自动合并单元格_第1张图片
vue iview table表格 render函数 自动合并单元格_第2张图片

<template>
  <div class="new-contract" style="height: 100%">
    <div class="serveTop">
      <div class="content-titles" style="padding-left: 24px">
        <Icon
          size="24"
          @click="backEvent"
          type="md-arrow-back"
          style="vertical-align: sub; cursor: pointer"
        />
        <span>{{ breadcrumbName }}</span>
      </div>
    </div>
    <div
      class="form-content"
      style="
        height: calc(100% - 160px);
        overflow: auto;
        padding: 0;
        margin: 24px;
        min-height: 0;
      "
    >
      <Form
        ref="executeForm"
        :model="executeForm"
        label-position="left"
        :rules="rules"
        :label-width="110"
      >
        <!-- <h2 class="titNew" style="padding: 0; margin-bottom: 20px">基本信息</h2> -->
        <Row style="padding: 20px 24px 0px">
          <Col span="8">
            <FormItem prop="userName" label="客户名称">
              <!-- <Select
                filterable
                clearable
                v-model="executeForm.userName"
                :disabled="executeForm.id || executeForm.customerId ? true : false"
                @on-change="handleUserNames"
                placeholder="请选择客户名称"
              >
                <Option
                  v-for="item in customerList"
                  :value="item.userName"
                  :key="item.id"
                >
                  {{ item.userName }}
                </Option>
              </Select> -->
              <Select
                clearable
                filterable
                v-model="executeForm.userName"
                :disabled="executeForm.id || executeForm.customerId ? true : false"
                @on-change="handleUserNames"
                placeholder="请选择客户名称"
              >
                <Option
                  v-for="items in customerList"
                  :value="items.userName"
                  :key="items.id"
                  >{{ items.userName }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="8" offset="1">
            <FormItem prop="taskType" label="客户类型">
              <Select
                disabled
                v-model="executeForm.customerType"
                placeholder="请选择客户类型"
              >
                <Option
                  v-for="item in customerType"
                  :value="item.dictKey"
                  :key="item.dictKey"
                >
                  {{ item.dictValue }}
                </Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Table
          class="tableStyles"
          max-height="420"
          height="300"
          :row-class-name="rowClassName"
          ref="tableStyles"
          :span-method="handleSpan"
          :columns="columns"
          :data="tableData"
        ></Table>
      </Form>
      <Button
        style="margin-top: 35px; margin-left: 90px"
        @click.stop="handleAddTable"
        type="primary"
        custom-icon="i-td i-td-add_px"
        >按合同编号添加</Button
      >
      <div style="padding: 35px 0px; margin-left: 90px">
        <Button
          type="primary"
          style="margin-right: 20px"
          @click.stop="handleok('executeForm')"
          >提交</Button
        >
        <Button @click="backEvent">取消</Button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import _ from "lodash";
import moment from "moment";
import { isEmail } from "@/utils/validate";
import { fetchDictList } from "@/api/Common";
import { getBussinessCodeList, getProductNameList} from '../../../api/taskServerV3';
export default {
  name: "newDataPayManager",
  data: function () {
    const _this = this
    const validateClass = (rule, value, callback) => {
      const max =
        value.length &&
        value.some((s) => {
          return s.length > 30;
        });
      const isEm =
        value.length &&
        value.some((m) => {
          return !isEmail(m);
        });
      if (!value.length) {
        callback();
      } else if (max) {
        callback(new Error("每项最多支持30个字符"));
      } else if (isEm) {
        callback(new Error("请输入正确的邮箱格式"));
      } else {
        callback();
      }
    };
    return {
      addOff: false,
      customerInfo: {},
      customerType: [],
      customerList: [],
      customerPay: [],
      rowKey: 0,
      columns: [
        {
          title: "序号",
          width: 70,
          render: (h, params) => {
            return h("span", params.index + 1);
          },
        },
        {
          key: "id2",
          minWidth: 240,
          renderHeader: (h, params) => {
            return h("div", [
              h("span", "合同编号"),
              h(
                "span",
                {
                  style: {
                    color: "#e62d2d",
                    fontSize: "14px",
                    fontFamily: 'SimSun'
                  },
                },
                "*"
              ),
            ]);
          },
          render: (h, params) => {
            if (params.row._index === _this.rowKey || params.row.isShowCompen) {
              return h("Select", {
                props: {
                  value: params.row.businessCode,
                  placeholder: "请选择合同编号",
                },
                domProps: {
                  id: "price" + params.index,
                },
                on: {
                  'on-change': (val) => {
                    this.tableData.forEach((ele,index) =>{
                      if(index == params.row._index){
                        ele.businessCode = val;
                      }
                    })
                  },
                },
              }, [
                _this.bussinessCodeList.map((val)=>{ //dataList就是要展示的数组
                  return h('Option', {
                    props: {value: val.businessCode}  
                  },`${val.businessCode}(${val.businessName})`);  
                })
              ]);
            }
            return h("div", params.row.businessCode);
          },
        },
        {
          key: "id",
          minWidth: 280,
          renderHeader: (h, params) => {
            return h("div", [
              h("span", "合同产品名称"),
              h(
                "span",
                {
                  style: {
                    color: "#e62d2d",
                    fontSize: "14px",
                    fontFamily: 'SimSun'
                  },
                },
                "*"
              ),
            ]);
          },
          render: (h, params) => {
            if (params.row._index === _this.rowKey || _this.rowKey == null) {
              return h("Select", {
                props: {
                  value: params.row.productId,
                  placeholder: "请选择合同产品名称",
                  filterable: true,
                  clearable: true,
                  labelInValue: true,
                  // remoteMethod: query => {
                  //   _this.proRemoteMethod(query, params.row._index)
                  // }
                },
                domProps: {
                  id: "price" + params.index,
                },
                on: {
                  'on-change': (val) => {
                    // params.row.productId = val;
                    _this.tableData.forEach((ele,index) =>{
                      if(index == params.row._index){
                        ele.productId = val.value;
                        ele.productName = val.label
                      }
                    })
                  },
                },
              }, [
                h('OptionGroup', {
                  props: {
                    label: '合同产品'
                  }
                }, [
                  _this.contractList.map((val)=>{ //dataList就是要展示的数组
                    return h('Option', {
                      props: {value: val.id}  
                    },`${val.productName}(${val.classificationName})`);  
                  })
                ]),
                h('OptionGroup', {
                  props: {
                    label: '非合同产品'
                  }
                }, [
                  _this.nonContractList.map((val)=>{ //dataList就是要展示的数组
                    return h('Option', {
                      props: {value: val.id}  
                    },`${val.productName}(${val.classificationName})`);  
                  })
                ])
              ]);
            }
            return h("div", params.row.productName);
          },
        },
        {
          key: "totalBusiness",
          minWidth: 160,
          renderHeader: (h, params) => {
            return h("div", [
              h("span", "业务总量"),
              h(
                "span",
                {
                  style: {
                    color: "#e62d2d",
                    fontSize: "14px",
                    fontFamily: 'SimSun'
                  },
                },
                "*"
              ),
            ]);
          },
          render: (h, params) => {
            if (params.row._index === _this.rowKey || _this.rowKey == null) {
              return h("InputNumber", {
                props: {
                  value: params.row.totalBusiness,
                  placeholder: "请输入业务总量",
                  min: 0
                },
                style: {
                  width: "100%",
                },
                domProps: {
                  id: "price" + params.index,
                },
                on: {
                  'on-change': (val) => {
                    // params.row.totalBusiness = val;
                    _this.tableData.forEach((ele,index) =>{
                      if(index == params.row._index){
                        ele.totalBusiness = val;
                      }
                    })
                  },
                },
              });
            }
            return h("div", params.row.totalBusiness);
          },
        },
        {
          title: "业务次数",
          minWidth: 160,
          key: "businessNums",
          render: (h, params) => {
            if (params.row._index === _this.rowKey || _this.rowKey == null) {
              return h("InputNumber", {
                props: {
                  value: params.row.businessNums,
                  placeholder: "请输入业务次数",
                  min: 0
                },
                style: {
                  width: "100%",
                },
                domProps: {
                  id: "price" + params.index,
                },
                on: {
                  'on-change': (val) => {
                    // params.row.businessNums = val;
                    _this.tableData.forEach((ele,index) =>{
                      if(index == params.row._index){
                        ele.businessNums = val;
                      }
                    })
                  },
                },
              });
            }
            return h("div", params.row.businessNums);
          },
        },
        {
          title: "交付来源",
          minWidth: 200,
          key: "id",
          render: (h, params) => {
            if (params.row._index === _this.rowKey || _this.rowKey == null) {
              return h("Select", {
                props: {
                  value: params.row.deliverySource,
                  placeholder: "请选择交付来源",
                  multiple: true,
                },
                domProps: {
                  id: "price" + params.index,
                },
                on: {
                  'on-change': (val) => {
                    _this.tableData.forEach((ele,index) =>{
                      if(index == params.row._index){
                        ele.deliverySource = val
                      }
                    })
                  },
                },
              }, [
                _this.customerPay.map((val)=>{ //dataList就是要展示的数组
                  return h('Option', {
                    props: {value: val.dictKey}  
                  },val.dictValue);  
                })
              ]);
            }
            return h("div", params.row.deliverySource ? params.row.deliverySource.join(',') : '');
          },
        },
        {
          title: "交付时间",
          minWidth: 220,
          key: "deliveryTime",
          render: (h, params) => {
            if (params.row._index === _this.rowKey || _this.rowKey == null) {
              return h("DatePicker", {
                props: {
                  value: params.row.deliveryTime,
                  placeholder: "请选择交付时间",
                  type: "datetime",
                },
                domProps: {
                  id: "price" + params.index,
                },
                on: {
                  'on-change': (val) => {
                    // params.row.deliveryTime = val;
                    _this.tableData.forEach((ele,index) =>{
                      if(index == params.row._index){
                        ele.deliveryTime = val;
                      }
                    })
                  },
                },
              });
            }
            return h("div", params.row.deliveryTime);
          },
        },
        {
          title: "收入",
          minWidth: 160,
          key: "revenue",
          render: (h, params) => {
            if (params.row._index === _this.rowKey || _this.rowKey == null) {
              return h("InputNumber", {
                props: {
                  value: params.row.revenue,
                  placeholder: "请输入收入",
                  min: 0
                },
                style: {
                  width: "100%",
                },
                domProps: {
                  id: "price" + params.index,
                },
                on: {
                  'on-change': (val) => {
                    this.tableData.forEach((ele,index) =>{
                      if(index == params.row._index){
                        ele.revenue = val;
                        ele.finalRevenue = ele.adjustIncome + ele.revenue
                      }
                    })
                  },
                },
              });
            }
            return h("div", params.row.revenue);
          },
        },
        {
          title: "核增核减",
          minWidth: 160,
          key: "adjustIncome",
          render: (h, params) => {
            if (params.row._index === _this.rowKey || _this.rowKey == null) {
              return h("InputNumber", {
                props: {
                  value: params.row.adjustIncome,
                  placeholder: "请输入核增核减",
                  min: 0
                },
                style: {
                  width: "100%",
                },
                domProps: {
                  id: "price" + params.index,
                },
                on: {
                  'on-change': (val) => {
                    this.tableData.forEach((ele,index) =>{
                      if(index == params.row._index){
                        ele.adjustIncome = val;
                        ele.finalRevenue = ele.adjustIncome + ele.revenue
                      }
                    })
                  },
                },
              });
            }
            return h("div", params.row.adjustIncome);
          },
        },
        {
          title: "最终的确认收入",
          minWidth: 160,
          key: "finalRevenue",
          render: (h, params) => {
            if (params.row._index === _this.rowKey || _this.rowKey == null) {
              return h("Input", {
                props: {
                  value: params.row.finalRevenue,
                  disabled: true,
                  placeholder: "请输入最终的确认收入",
                },
              });
            }
            return h("div", params.row.finalRevenue);
          },
        },
        {
          title: " ",
          align: "center",
          fixed: "right",
          width: 100,
          render: (h, params) =>
            h("div", [
              h(
                "Tooltip",
                {
                  props: {
                    content: "确认",
                    placement: "top",
                    transfer: true,
                  },
                  style: {
                    marginRight: "5px",
                    display:
                      _this.rowKey == params.row._index
                        ? "inline-block"
                        : "none",
                  },
                },
                [
                  h("Icon", {
                    props: {
                      size: 21,
                      type: "ios-checkmark-circle",
                    },
                    style: {
                      cursor: "pointer",
                      verticalAlign: "text-top",
                    },
                    nativeOn: {
                      click: (event) => {
                        event.stopPropagation();
                        if (!_this.getRequstNode()) {
                          _this.rowKey = -1;
                          _this.addOff = true;
                          _this.tableData.forEach((ele) =>{
                            if (ele.id == params.row.id){
                              params.row.isShowCompen = false;
                            }
                          })
                          _this.checkSameData(_this.tableData);
                          _this.assembleData(_this.tableData);
                        } else {
                          _this.$Message.info('必填信息不能为空');
                        }
                      },
                    },
                  }),
                ]
              ),
              // h(
              //   "Tooltip",
              //   {
              //     props: {
              //       content: "取消",
              //       placement: "top",
              //       transfer: true,
              //     },
              //     style: {
              //       marginRight: "5px",
              //       display:
              //         _this.rowKey == params.row._index &&
              //         _this.tableData.length > 1
              //           ? "inline-block"
              //           : "none",
              //     },
              //   },
              //   [
              //     h("Icon", {
              //       props: {
              //         size: 21,
              //         type: "md-remove-circle",
              //       },
              //       style: {
              //         cursor: "pointer",
              //         verticalAlign: "text-top",
              //       },
              //       nativeOn: {
              //         click: (event) => {
              //           event.stopPropagation();

              //           this.tableData.forEach((ele,index) =>{
              //             if(index == params.row._index){
              //               ele.isShowCompen = false;
              //             }
              //           })

              //           _this.rowKey = -1;
              //         },
              //       },
              //     }),
              //   ]
              // ),
              h(
                "Tooltip",
                {
                  props: {
                    content: "编辑",
                    placement: "top",
                    transfer: true,
                  },
                  style: {
                    marginRight: "5px",
                    display:
                      _this.rowKey !== params.row._index && _this.rowKey!==null
                        ? "inline-block"
                        : "none",
                  },
                },
                [
                  h("Icon", {
                    props: {
                      size: 21,
                      type: "ios-create",
                    },
                    style: {
                      cursor: "pointer",
                      verticalAlign: "text-top",
                    },
                    nativeOn: {
                      click: (event) => {
                        event.stopPropagation();
                        // if (!_this.getRequstNode()) {
                          
                        // } else {
                        //   _this.$Message.info('必填信息不能为空');
                        // }
                        _this.rowKey = params.row._index;
                      },
                    },
                  }),
                ]
              ),
              h(
                "Tooltip",
                {
                  props: {
                    content: "删除",
                    placement: "top",
                    transfer: true,
                  },
                  style: {
                    marginRight: "5px",
                    display:
                      _this.tableData.length > 1
                        ? "inline-block"
                        : "none",
                  },
                },
                [
                  h("Icon", {
                    props: {
                      size: 21,
                      type: "md-close-circle",
                    },
                    style: {
                      cursor: "pointer",
                      verticalAlign: "text-top",
                    },
                    nativeOn: {
                      click: (event) => {
                        event.stopPropagation();
                        _this.tableData.forEach((ele, index) => {
                          if (index == params.row._index) {
                            _this.tableData.splice(index, 1);
                          }
                        });
                        _this.checkSameData(_this.tableData);
                        _this.assembleData(_this.tableData);
                        // console.log(_this.tableData);
                      },
                    },
                  }),
                ]
              ),
            ]),
        },
      ],
      contractList: [],
      nonContractList: [],
      tableData: [
      ],
      userObj: {},
      deSrcList: [
        {
          label: "O",
          value: 1,
        },
        {
          label: "M",
          value: 2,
        },
        {
          label: "域",
          value: 3,
        },
      ],
      statusList: [
        {
          label: "审批中",
          value: 0,
        },
        {
          label: "进行中",
          value: 1,
        },
        {
          label: "已结束",
          value: 2,
        },
        {
          label: "已废弃",
          value: 3,
        },
      ],
      params: {},
      //是否为编辑页面
      proLoading: false,
      breadcrumbName: "创建",
      customerIndustry: [],
      bussinessCodeList: [],
      // 数据交付运营
      productTypeList: [],
      options: [],
      productLineList: [],
      executeForm: {
        userName: "",
        customerType: '',
      },
      //查询表单校验
      rules: {
        createTime: [
          {
            required: true,
            message: "该项不能为空",
            type: "date",
            trigger: "change",
          },
        ],
        creator: [{ required: true, message: "该项不能为空", trigger: "blur" }],
        submitDepartment: [
          { required: true, message: "该项不能为空", trigger: "blur" },
        ],
        deliverySrc: [
          {
            required: true,
            type: "number",
            message: "该项不能为空",
            trigger: "change",
          },
        ],
        taskStatus: [
          {
            required: true,
            type: "number",
            message: "该项不能为空",
            trigger: "change",
          },
        ],
        userName: [
          { required: true, message: "该项不能为空", trigger: "blur" },
        ],
        customerName: [
          { required: true, message: "该项不能为空", trigger: "blur" },
        ],
        taskType: [
          { required: false, message: "该项不能为空", trigger: "blur" },
          // { type: "string", validator: validateNameCnEn, trigger: "blur" },
        ],
        solutionDismantling: [
          { required: false, message: "该项不能为空", trigger: "blur" },
          // { type: "string", validator: validateNameCnEn, trigger: "blur" },
        ],
        workingHours: [
          { required: false, message: "该项不能为空", trigger: "blur" },
        ],
        deliveryInstructions: [
          { required: false, message: "该项不能为空", trigger: "blur" },
        ],
        resultPath: [
          { required: false, message: "该项不能为空", trigger: "blur" },
        ],
        currentHandler: [
          {
            required: false,
            type: "array",
            validator: validateClass,
            trigger: "change",
          },
        ],
      },
    };
  },
  computed: {},
  components: {},
  methods: {
    querypro() {
      this.proLoading = true;
    },
    proRemoteMethod: _.debounce(function (query,item) {
      const searchName = query ? query.trim() : query;
      if (searchName) {
        getProductNameList({
          pageNo: 1,
          pageSize: 10000,
          userName: this.executeForm.userName,
          productName: searchName, //搜索关键字
        }).then((res) => {
          this.proLoading = false;
          const list = res.data.data.nonContractList.map((items) => {
            return {
              value: items.id,
              label: items.productName,
              id: items,
            };
          });
          this.tableData.forEach((t,index) =>{
            if (index == item) {
              t.customerpro = list
            }
          })
        });
      } else {
        this.proLoading = false;
        // item.customerpro = [];
      }
    }, 500),
    handleUserNames(){
      // console.log(this.tableData);
      this.tableData = [
        {
          "userName": "",
          "businessCode": "",
          "productId": '',
          "totalBusiness": "",
          "businessNums": '',
          "deliverySource": "",
          "deliveryTime": "",
          "revenue": 0,
          "adjustIncome": 0,
          "finalRevenue": 0,
          customerpro: []
        }
      ];
      this.rowKey = 0;
      getBussinessCodeList({
        userName: this.executeForm.userName
      }).then((res) =>{
        if (res.data.status == 200) {
          if (res.data.data.length){
            this.bussinessCodeList = res.data.data;
            this.tableData.forEach((ele) =>{
              ele.businessCode = res.data.data[0].businessCode;
            })
          } else {
            this.bussinessCodeList = [];
            this.tableData.forEach((ele) =>{
              ele.businessCode = '';
            })
          }
        }
      })

      if (!this.executeForm.customerType){
        const result = this.customerList.filter((item) => {return item.userName == this.executeForm.userName})
        this.executeForm.customerType = result.length && result[0].customerType
      }

      this.getProductNames();
    },
    rowClassName() {
      return "row-info";
    },
    assembleData(data) {
      let names = [];
      // 筛选出不重复的 staff_no值,将其放到 names数组中
      data.forEach((e) => {
        if (!names.includes(e.businessCode)) {
          names.push(e.businessCode);
        }
      });
      let nameNums = [];
      // 将names数组中的 staff_no值设置默认合并0个单元格,放到 nameNums中
      names.forEach((e) => {
        nameNums.push({ businessCode: e, num: 0 });
      });
      // 计算每种 staff_no值所在行需要合并的单元格数
      data.forEach((e) => {
        nameNums.forEach((n) => {
          if (e.businessCode === n.businessCode) {
            n.num++;
          }
        });
      });
      // 将计算后的合并单元格数整合到 data中
      data.forEach((e) => {
        nameNums.forEach((n) => {
          if (e.businessCode === n.businessCode) {
            if (names.includes(e.businessCode)) {
              e.mergeColumn = n.num;
              // 删除已经设置过的值(防止被合并的单元格进到这个 if 语句中)
              names.splice(names.indexOf(n.businessCode), 1);
            } else {
              // 被合并的单元格设置为 0
              e.mergeColumn = 0;
            }
          }
        });
      });
      // 将整理后的数据交给表格渲染
      this.tableData = data;
    },
    checkSameData(tableData) {
      let cache = {}; // 存储的是键是staff_no的值,值是staff_no在indeces中数组的下标
      let indices = []; // 数组中每一个值是一个数组,数组中的每一个元素是原数组中相同staff_no的下标
      tableData.map((item, index) => {
        // eslint-disable-next-line camelcase
        let businessCode = item.businessCode;
        let _index = cache[businessCode];
        if (_index !== undefined) {
          indices[_index].push(index);
        } else {
          cache[businessCode] = indices.length;
          indices.push([index]);
        }
      });
      let result = [];
      indices.map((item) => {
        item.map((index) => {
          result.push(tableData[index]);
        });
      });
      this.tableData = result;
    },
    handleSpan({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1) {
        // 计算合并的行数列数
        let x = row.mergeColumn === 0 ? 0 : row.mergeColumn;
        let y = row.mergeColumn === 0 ? 0 : 1;
        return [x, y];
      }
    },
    handleAddTable() {
      if (!this.getRequstNode()) {
        this.tableData.forEach((t) =>{
          t.isShowCompen = false
        })
        this.tableData.push({
          "userName": "",
          "businessCode": "",
          "productId": '',
          "totalBusiness": "",
          "businessNums": '',
          "deliverySource": "",
          "deliveryTime": "",
          "revenue": 0,
          "adjustIncome": 0,
          "finalRevenue": 0,
          isShowCompen: true,
          customerpro: []
        });
        if (this.rowKey!== null){
          this.rowKey = this.tableData.length - 1;
        }
        this.checkSameData(this.tableData);
        this.assembleData(this.tableData);
      } else {
        this.$Message.info('必填信息不能为空');
      }
    },
    handleStatusEvent(data) {
      if (data == 2 || data == 3) {
        this.executeForm.taskStartTime = null;
      }
      if (data == 1) {
        this.executeForm.taskDoneTime = null;
      }
      if (data == 0) {
        this.executeForm.taskStartTime = null;
        this.executeForm.taskDoneTime = null;
      }
    },
    getProductLine() {
      let params = {
        pageNo: 1,
        pageSize: 500,
        keyWord: "",
      };
      let _this = this;
      axios
        .post("/page", params)
        .then((res) => {
          // _this.validateSvcCode = res.data;
          if (res.data.status == "200") {
            _this.productLine = res.data.data.data;
            _this.productLineList = res.data.data.data.map((ele) => {
              return {
                label: `${ele.name}`,
                value: `${ele.name}`,
                display: false,
              };
            });
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    // 数据运营
    handleok(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let params = [];
          this.tableData.forEach((ele) =>{
            params.push({
              "userName": this.executeForm.userName,
              "businessCode": ele.businessCode,
              "productId": ele.productId,
              "totalBusiness": ele.totalBusiness,
              "businessNums": ele.businessNums,
              "deliverySource": ele.deliverySource ? ele.deliverySource.join(',') : '',
              "deliveryTime": ele.deliveryTime,
              "revenue": ele.revenue,
              "adjustIncome": ele.adjustIncome,
              "finalRevenue":  ele.finalRevenue,
            })
          })

          if (this.getRequstNode()) return this.$Message.info('必填信息不能为空')

          if (this.executeForm.id) {
            // 编辑
            let _this = this;
            axios
              .post(
                `/update?id=${_this.executeForm.id}`,params
              )
              .then(res => {
                // _this.validateSvcCode = res.data;
                if (res.data.status == "200") {
                 _this.$Message.success("编辑成功");
                 _this.backEvent()
                } else {
                  _this.$Message.error(res.data.message);
                }
              })
              .catch(function(error) {
                console.log(error);
              });
          } else {
            let _this = this;
            axios
              .post(
                "/create",params
              )
              .then(res => {
                // _this.validateSvcCode = res.data;
                if (res.data.status == "200") {
                 _this.$Message.success("创建成功");
                 _this.backEvent()
                } else {
                  _this.$Message.error(res.data.message);
                }
              })
              .catch(function(error) {
                console.log(error);
              });
          }
        }
      });
    },
    cancelModalNow() {
      this.$refs["executeForm"].resetFields();
      this.resetDisable();
      this.$router.push({ name: "customerPayManager" });
    },
    handleProLineDel(jndex) {
      this.executeForm.productLines.forEach((it, index) => {
        if (index == jndex) {
          this.executeForm.productLines.splice(index, 1);
          this.productLineList.forEach((ele) => {
            if (ele.value == it.name) {
              ele.display = false;
            }
          });
        }
      });
    },
    handleProTypeDel(list, jndex) {
      list.forEach((item, index) => {
        if (index == jndex) {
          list.splice(index, 1);
        }
      });
    },
    handleProTypeEvent(list) {
      list.push({ type: "", deviceCount: 0 });
    },
    handleProLineEvent() {
      this.executeForm.productLines.push({
        name: "",
        productTypes: [{ type: "", deviceCount: 0 }],
      });
    },
    resetDisable() {
      this.productLineList.forEach((ele) => {
        ele.display = false;
      });
    },
    setDisable() {
      let productName = [];
      this.executeForm.productLines.forEach((item) => {
        if (item.name) {
          productName.push(item.name);
        }
      });
      this.productLineList.forEach((item) => {
        productName.forEach((ele) => {
          if (item.value == ele) {
            item.display = true;
          }
        });
      });
    },
    handleProLEvent(data, ele) {
      this.resetDisable();
      this.setDisable();
      // 产品分类
      this.productLine.forEach((item) => {
        if (item.name == data) {
          ele.productTypeList = item.classification.split(",").map((res) => {
            return {
              label: res,
              value: res,
            };
          });
        }
      });
    },
    handleCreate(val) {
      const isEm = isEmail(val);
      if (!isEm) return;
      this.options.push({
        value: val,
        label: val,
      });
    },
    backEvent() {
      this.$router.push({
        name: "customerPayManager",
      });
    },
    setDomNode() {
      // 追加静态dom
      const _this = this;
      _this.$nextTick(() => {
        const arrs = document.querySelector(".ivu-table-tbody").children;
        
        for (let i = 0; i < arrs.length; i += 1) {
          
          if (arrs[i].firstChild.querySelector("span")) {
            // 获取key
            let node = document.createElement("span");
            const keyName = arrs[i].firstChild.querySelector("span").innerHTML;
            node.setAttribute("id", keyName);
            node.innerHTML = "+";
            node.className = "ivu-span-dot";

            arrs[i].appendChild(node);

            node.addEventListener("click", function (e) {
              e.preventDefault(); //dom推荐的 标准写法
              const key = e.target.id;
              if (!_this.getRequstNode()) {
                _this.tableData.splice(key, 0, {
                  "userName": "",
                  "businessCode": _this.tableData[key-1].businessCode,
                  "productId": '',
                  "totalBusiness": "",
                  "businessNums": '',
                  "deliverySource": "",
                  "deliveryTime": "",
                  "revenue": 0,
                  "adjustIncome": 0,
                  "finalRevenue": 0,
                  customerpro: []
                });
                if (_this.rowKey !== null) {
                  const numStep = Number(_this.tableData.length) - Number(key);
                  if (numStep !==1){
                    _this.rowKey = +key
                  } else {
                    _this.rowKey = _this.tableData.length - 1;
                  }
                }
                _this.checkSameData(_this.tableData);
                _this.assembleData(_this.tableData);
              } else {
                _this.$Message.info('必填信息不能为空');
              }
              
            });
          }
        }

        
      });
    },
    // 查询必填项目
    getRequstNode(){
      const result = this.tableData.some((ele) =>{ return !ele.businessCode || !ele.totalBusiness || !ele.productId})
      return result
    },
    getDetail(rowId){
      let _this = this;
      axios
        .get("/detail", {
          params: {
            id: rowId,
          },
        })
        .then((res) => {
          if (res.data.status == "200") {
            this.executeForm.userName = res.data.data[0].userName;
            this.executeForm.customerType = res.data.data[0].customerType;

            res.data.data.forEach((item) =>{
              item.deliverySource = item.deliverySource.split(',');
              item.customerpro = [];
              console.log(item);
              getProductNameList({
                pageNo: 1,
                pageSize: 10000,
                userName: item.userName,
                productName: item.productName, //搜索关键字
              }).then((res) => {
                this.proLoading = false;
                const list = res.data.data.nonContractList.map((items) => {
                  return {
                    value: items.id,
                    label: items.productName,
                    id: items,
                  };
                });
                item.customerpro = list
              });

            })

            getBussinessCodeList({
              userName: this.executeForm.userName
            }).then((res) =>{
              if (res.data.status == 200) {
                if (res.data.data.length){
                  this.bussinessCodeList = res.data.data;
                } else {
                  this.bussinessCodeList = [];
                }
              }
            })

            _this.tableData = res.data.data;

            _this.getProductNames();

            _this.checkSameData(_this.tableData);
            _this.assembleData(_this.tableData);


            // console.log(_this.tableData);
          }
        });
    },
    //查询客户详情
    getDetailC(customerCode) {
      let _this = this;
      axios
        .get("/detail", {
          params: {
            id: customerCode,
          },
        })
        .then((res) => {
          if (res.data.status == "200") {
             _this.executeForm.userName = res.data.data.userName;
             _this.executeForm.customerType = res.data.data.customerType;
            _this.handleUserNames();
            _this.getProductNames();
          }
        });
    },
    // 获取产品名称
    getProductNames(){
      getProductNameList({
        pageNo: 1,
        pageSize: 10000,
        userName: this.executeForm.userName,
      }).then((res) => {
        // console.log(res.data.data);
        this.contractList = res.data.data.contractList;
        this.nonContractList = res.data.data.nonContractList
      });
    }
  },
  mounted: function () {
    // 获取当前时间
    this.getProductLine();
    this.userObj = JSON.parse(sessionStorage.getItem("users"));
    this.params = JSON.parse(sessionStorage.getItem("executeFormPay"));
    
    fetchDictList({ dictType: 56, isAll: false }, (res) => {
      this.customerType = res;
    });
    fetchDictList({ dictType: 58, isAll: false }, (res) => {
      this.customerPay = res;
    });

    let _this = this;
    axios
      .post("/list", {
        pageNo: 1,
        pageSize: 10000,
      })
      .then((res) => {
        // _this.validateSvcCode = res.data;
        if (res.data.status == "200") {
          _this.customerList = res.data.data.data;
          // _this.tableData = res.data.data.data;
        }
      })
      .catch(function (error) {
        console.log(error);
      });
    this.setDomNode();
    if (this.$route.query && this.$route.query.customerId) {
      // 从客户管理
      this.getDetailC(this.$route.query.customerId);
      this.breadcrumbName = "创建客户交付";
      this.executeForm.customerId = this.$route.query.customerId
    } else if (this.$route.query && this.$route.query.rowId) {
      // 从客户交付管理
      this.getDetail(this.$route.query.rowId);
      this.executeForm.id = this.$route.query.rowId;
      this.breadcrumbName = "编辑客户交付";
      this.rowKey = null;
    } else {
      this.breadcrumbName = "创建客户交付";
      this.rowKey = 0;
    }


    this.tableData.push({
      "userName": "",
      "businessCode": "",
      "productId": '',
      "totalBusiness": "",
      "businessNums": '',
      "deliverySource": "",
      "deliveryTime": "",
      "revenue": 0,
      "adjustIncome": 0,
      "finalRevenue": 0,
      customerpro: []
    })
  },
  watch: {
    tableData(val) {
      val.forEach((v) =>{
        v.deliveryTime = v.deliveryTime ? v.deliveryTime : moment(new Date()).format("YYYY-MM-DD HH:mm:ss");;
        v.finalRevenue = v.revenue + v.adjustIncome
      })
      this.setDomNode();
    },
  },
};
</script>
<style scoped>
.onlyProductLines /deep/ .ivu-col {
  position: initial;
}
.tableStyles /deep/ .ivu-table-row {
  position: relative;
}
.tableStyles /deep/ .ivu-table-row .ivu-span-dot {
  position: absolute;
  display: none;
  left: 41%;
  top: 35px;
  padding: 0px 20px;
  border-radius: 3px;
  border: 1px solid #2185f0;
  color: #2185f0;
  font-weight: bold;
  z-index: 4;
  cursor: pointer;
  font-size: 12px;
  background: #fff;
}
.tableStyles /deep/ .ivu-table-tbody {
  cursor: pointer;
}
.tableStyles /deep/ .row-info:hover .ivu-span-dot {
  display: block;
}
</style>
<style>
.userStyle .ivu-select .ivu-select-dropdown {
  width: inherit !important;
}
</style>

你可能感兴趣的:(render,vue.js,view,design,javascript)