
<template>
  <div>
    <Table
      ref="prepareTable"
      :columns="columnsList"
      :data="thisTableData"
      border
      disabled-hover
      @on-selection-change="onSelectionChange"
      @on-select-all="onSelectAll"
      @on-select="onSelect"
      @on-select-cancel="onSelectCannel"
    ></Table>
  </div>
</template>
<script>
import { mapState, mapGetters, mapMutations } from 'vuex';
import OperatorInfo from './OperatorInfo.vue';

let vm;
const incellEditBtn = (vm, h, param) => {
  if (vm.hoverShow) {
    return h(
      'div',
      {
        class: {
          'show-edit-btn': vm.hoverShow
        }
      },
      [
        h('Button', {
          props: {
            type: 'text',
            icon: 'edit'
          },
          on: {
            click: event => {
              vm.edittingStore[param.index].edittingCell[
                param.column.key
              ] = true;
              vm.thisTableData = JSON.parse(JSON.stringify(vm.edittingStore));
            }
          }
        })
      ]
    );
  } else {
    return h('Button', {
      props: {
        type: 'text',
        icon: 'edit'
      },
      on: {
        click: event => {
          vm.edittingStore[param.index].edittingCell[param.column.key] = true;
          vm.thisTableData = JSON.parse(JSON.stringify(vm.edittingStore));
        }
      }
    });
  }
};
const saveIncellEditBtn = (vm, h, param) => {
  return h('Button', {
    props: {
      type: 'text',
      icon: 'checkmark'
    },
    on: {
      click: event => {
        // 编辑准备付款金额
        vm.server
          .savePaymentPreparation({
            payBatchDto: {
              // 付款准备批ID
              batchId: param.row.batchId
            },
            payLineDetails: [
              {
                // 付款行明细ID
                payLineDetailId: param.row.payLineDetailId,
                // 付款准备批ID
                batchId: param.row.batchId,
                payLineId: param.row.payLineId,
                // 准备付款金额
                payAmount: vm.edittingStore[param.index].payAmount
              }
            ]
          })
          .then(response => {
            vm.basicInfoComponent.init();
            vm.paymentApplyInfoComponent.init();
            vm.paymentPreparationInfoComponent.init();
          });
        vm.edittingStore[param.index].edittingCell[param.column.key] = false;
        vm.thisTableData = JSON.parse(JSON.stringify(vm.edittingStore));
        vm.$emit('input', vm.handleBackdata(vm.thisTableData));
        vm.$emit(
          'on-cell-change',
          vm.handleBackdata(vm.thisTableData),
          param.index,
          param.column.key
        );
      }
    }
  });
};
const cellInput = (vm, h, param, item) => {
  return h('Input', {
    props: {
      type: 'text',
      value: vm.edittingStore[param.index][item.key]
    },
    on: {
      'on-change'(event) {
        if (
          /^(\d+|\d+\.\d{1,2})$/.test(event.target.value) ||
          /^([0-9]{1,}[.][0-9]*)$/.test(event.target.value)
        ) {
          const key = item.key;
          vm.edittingStore[param.index][key] = event.target.value;
        } else {
          vm.$Message.warning('必须为数字');
          event.target.value = param.row.payAmount;
        }
      }
    }
  });
};
export default {
  name: 'CanEditTable',
  components: {
    OperatorInfo
  },
  computed: {
    ...mapState('createPaymentPreparation', {
      basicInfoComponent: state => state.basicInfoComponent,
      paymentApplyInfoComponent: state => state.paymentApplyInfoComponent,
      paymentPreparationInfoComponent: state =>
        state.paymentPreparationInfoComponent,
      selections: state => state.paymentSelects.selections
    })
  },
  props: {
    refs: String,
    // columnsList: Array,
    value: Array,
    url: String,
    server: Object,
    editIncell: {
      type: Boolean,
      default: false
    },
    hoverShow: {
      type: Boolean,
      default: false
    },
    row: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      columns: [],
      thisTableData: [],
      edittingStore: [],
      selectAllFlag: '2', // 2=>全部未选中，3=>部分选中，4=>全部选中
      selectStatus: false,
      columnsList: [
        {
          type: 'index',
          width: 60,
          title: '序号',
          align: 'left'
        },
        {
          type: 'selection',
          width: 60,
          align: 'center',
          fixed: 'left',
          disabled: 'true'
        },
        {
          title: '付款方式',
          align: 'left',
          width: 120,
          key: 'paymentModeName',
          render: (h, params) => {
            return h(
              'span',
              {
                attrs: {
                  title: params.row.paymentModeName
                }
              },
              params.row.paymentModeName
            );
          }
        },
        {
          title: '准备付款金额',
          align: 'left',
          width: 150,
          key: 'payAmount'
        },
        {
          title: '付款状态',
          align: 'left',
          width: 140,
          key: 'statusName',
          render: (h, params) => {
            return h(
              'span',
              {
                attrs: {
                  title: params.row.statusName
                }
              },
              params.row.statusName
            );
          }
        },
        {
          title: '付款申请单',
          align: 'left',
          width: 200,
          key: 'payRequestClaimNo',
          render: (h, params) => {
            return h(
              'span',
              {
                attrs: {
                  title: params.row.payRequestClaimNo
                }
              },
              params.row.payRequestClaimNo
            );
          }
        },
        {
          title: '行号',
          align: 'left',
          width: 80,
          key: 'payRequestLineId',
          render: (h, params) => {
            return h(
              'span',
              {
                attrs: {
                  title: params.row.payRequestLineId
                }
              },
              params.row.payRequestLineId
            );
          }
        },
        {
          title: '供应商',
          align: 'left',
          width: 240,
          key: 'vendorName',
          render: (h, params) => {
            return h(
              'span',
              {
                attrs: {
                  title: params.row.vendorName
                }
              },
              params.row.vendorName
            );
          }
        },
        {
          title: '收款账户',
          align: 'left',
          width: 240,
          key: 'vendorAccountNo',
          render: (h, params) => {
            return h(
              'span',
              {
                attrs: {
                  title: params.row.vendorAccountNo
                }
              },
              params.row.vendorAccountNo
            );
          }
        },
        {
          title: '初审会计',
          align: 'left',
          width: 120,
          key: 'accountantEmpName',
          render: (h, params) => {
            return h(
              'span',
              {
                attrs: {
                  title: params.row.accountantEmpName
                }
              },
              params.row.accountantEmpName
            );
          }
        },
        {
          title: '支付时间',
          align: 'left',
          width: 300,
          key: 'payTime',
          render: (h, params) => {
            let payTime = params.row.payTime;
            return h('DatePicker', {
              props: {
                value: params.row.payTime,
                transfer: true,
                type: 'datetime',
                confirm: true
              },
              on: {
                'on-change': (data) => {
                  payTime = data;
                },
                'on-ok': () => {
                  vm.thisTableData[params.index].payTime = payTime;
                  this.server.updatePayTime({
                    payTime: payTime,
                    payLineDetailId: vm.thisTableData[params.index].payLineDetailId
                  }).then(response => {
                    if (response.statusCode == -1) {
                      this.$Message.warning(response.msg);
                      vm.thisTableData[params.index].payTime = params.row.payTime;
                    } else {
                      this.$Message.success('修改成功');
                      vm.thisTableData[params.index].payTime = payTime;
                    }
                  });
                }
              }

            }
            );
          }
        },
        {
          title: '申请金额',
          align: 'right',
          width: 120,
          key: 'applyAmount',
          render: (h, params) => {
            return h(
              'span',
              {
                attrs: {
                  title: params.row.applyAmount
                }
              },
              params.row.applyAmount
            );
          }
        },
        {
          title: '申请人',
          align: 'left',
          width: 120,
          key: 'applyEmpName',
          render: (h, params) => {
            return h(
              'span',
              {
                attrs: {
                  title: params.row.applyEmpName
                }
              },
              params.row.applyEmpName
            );
          }
        },
        {
          title: '付款备注',
          align: 'left',
          width: 300,
          key: 'payRemark',
          render: (h, params) => {
            return h(
              'span',
              {
                attrs: {
                  title: params.row.payRemark
                }
              },
              params.row.payRemark
            );
          }
        },
        {
          title: '结算号',
          align: 'left',
          width: 120,
          key: 'settlementNum',
          render: (h, params) => {
            return h(
              'span',
              {
                attrs: {
                  title: params.row.settlementNum
                }
              },
              params.row.settlementNum
            );
          }
        },
        // {
        //   title: "项目名称",
        //   align: "left",
        //   width: 300,
        //   key: "projectName",
        //   render: (h, params) => {
        //     return h(
        //       "span",
        //       {
        //         attrs: {
        //           title: params.row.projectName
        //         }
        //       },
        //       params.row.projectName
        //     );
        //   }
        // },
        // {
        //   title: "项目编码",
        //   align: "left",
        //   width: 200,
        //   key: "projectCode",
        //   render: (h, params) => {
        //     return h(
        //       "span",
        //       {
        //         attrs: {
        //           title: params.row.projectCode
        //         }
        //       },
        //       params.row.projectCode
        //     );
        //   }
        // },
        {
          title: '币种',
          align: 'left',
          width: 120,
          key: 'currency',
          render: (h, params) => {
            const val = params.row.currency;
            const list =
              vm.$store.state.createPaymentPreparation.valueSet.currency ||
              [];
            let text = '';
            list.forEach(function(item) {
              if (item.value == val) {
                text = item.label;
                return false;
              }
            });
            return h('div', {}, text);
          }
        },
        {
          title: '银行账户类型',
          align: 'left',
          width: 150,
          key: 'accountType',
          render: (h, params) => {
            return h(
              'span',
              {
                attrs: {
                  title: params.row.accountType
                }
              },
              params.row.accountType
            );
          }
        },
        {
          title: '付款操作记录',
          align: 'left',
          width: 150,
          render: (h, params) => {
            return h('RowTools', {
              props: {
                data: [
                  {
                    type: 'button',
                    text: '付款操作记录',
                    handle: () => {
                      this.showOperatorInfoWin(params.row);
                    }
                  }
                ]
              }
            });
          }
        },
        {
          title: '消息',
          align: 'left',
          width: 300,
          key: 'errorMessage',
          render: (h, params) => {
            return h(
              'span',
              {
                attrs: {
                  title: params.row.errorMessage
                }
              },
              params.row.errorMessage
            );
          }
        }
      ]
    };
  },
  created() {
    this.init();
  },
  mounted() {
    vm = this;
    this.$store.state.createPaymentPreparation.paymentSelects.selections = [];
  },
  methods: {
    ...mapMutations('createPaymentPreparation', [
      'setBasicInfo',
      'setPaymentApplyInfo'
    ]),
    // 显示操作信息
    showOperatorInfoWin(row) {
      new this.$pageModal(OperatorInfo, {
        props: {
          title: '付款操作记录',
          payLineDetailId: row.payLineDetailId,
          server: vm.server
        }
      });
    },
    init() {
      const editableCell = this.columnsList.filter(item => {
        if (item.editable) {
          if (item.editable === true) {
            return item;
          }
        }
      });
      for (let i = 0; i < this.value.length; i++) {
        // this.value[i]._checked=false;
        this.$set(this.value[i], '_checked', false);
      }
      const cloneData = JSON.parse(JSON.stringify(this.value));
      let res = [];
      res = cloneData.map((item, index) => {
        let isEditting = false;
        if (this.thisTableData[index]) {
          if (this.thisTableData[index].editting) {
            isEditting = true;
          } else {
            for (const cell in this.thisTableData[index].edittingCell) {
              if (this.thisTableData[index].edittingCell[cell] === true) {
                isEditting = true;
              }
            }
          }
        }
        if (isEditting) {
          return this.thisTableData[index];
        } else {
          this.$set(item, 'editting', false);
          const edittingCell = {};
          editableCell.forEach(item => {
            edittingCell[item.key] = false;
          });
          this.$set(item, 'edittingCell', edittingCell);
          return item;
        }
      });
      this.thisTableData = res;
      this.edittingStore = JSON.parse(JSON.stringify(this.thisTableData));
      this.columnsList.forEach(item => {
        if (item.editable) {
          item.render = (h, param) => {
            const currentRow = this.thisTableData[param.index];
            if (!currentRow.editting) {
              if (this.editIncell) {
                return h(
                  'Row',
                  {
                    props: {
                      type: 'flex',
                      align: 'middle',
                      justify: 'center'
                    }
                  },
                  [
                    h(
                      'Col',
                      {
                        props: {
                          span: '22'
                        }
                      },
                      [
                        !currentRow.edittingCell[param.column.key]
                          ? h('span', currentRow[item.key])
                          : cellInput(this, h, param, item)
                      ]
                    ),
                    h(
                      'Col',
                      {
                        props: {
                          span: '2'
                        }
                      },
                      [
                        currentRow.edittingCell[param.column.key]
                          ? saveIncellEditBtn(this, h, param)
                          : incellEditBtn(this, h, param)
                      ]
                    )
                  ]
                );
              } else {
                return h('span', currentRow[item.key]);
              }
            } else {
              return h('Input', {
                props: {
                  type: 'text',
                  value: currentRow[item.key]
                },
                on: {
                  'on-change'(event) {
                    const key = param.column.key;
                    vm.edittingStore[param.index][key] = event.target.value;
                  }
                }
              });
            }
          };
        }
        if (item.handle) {
          item.render = (h, param) => {
            const currentRowData = this.thisTableData[param.index];
            const children = [];
            item.handle.forEach(item => {
              if (item === 'edit') {
                children.push(editButton(this, h, currentRowData, param.index));
              } else if (item === 'delete') {
                children.push(
                  deleteButton(this, h, currentRowData, param.index)
                );
              }
            });
            return h('div', children);
          };
        }
      });
    },
    handleBackdata(data) {
      const clonedData = JSON.parse(JSON.stringify(data));
      clonedData.forEach(item => {
        delete item.editting;
        delete item.edittingCell;
        delete item.saving;
      });
      return clonedData;
    },
    onSelectAll(selection) {
      const self = this;
      let allFlag = false;
      if (self.selections.length == 0) {
        for (let j = 0; j < self.thisTableData.length; j++) {
          let flag = true;
          for (let k = 0; k < self.selections.length; k++) {
            if (
              self.thisTableData[j].payLineDetailId ==
                self.selections[k].payLineDetailId
            ) {
              flag = false;
              break;
            }
          }
          if (flag) {
            self.selections.push(self.thisTableData[j]);
            flag = true;
          }
        }
        this.selectStatus = true;
      } else {
        for (let m = 0; m < self.selections.length; m++) {
          for (let n = 0; n < selection.length; n++) {
            if (self.selections[m].statusName != selection[n].statusName) {
              allFlag = true;
              break;
            }
          }
        }
        if (allFlag) {
          for (let g = 0; g < self.thisTableData.length; g++) {
            self.$set(self.thisTableData[g], '_checked', true);
            self.$forceUpdate();
          }
          setTimeout(() => {
            for (let i = 0; i < self.thisTableData.length; i++) {
              self.$set(self.thisTableData[i], '_checked', false);
              self.$Message.info('请选择状态一样的明细行');
            }
          }, 10);
        } else {
          for (let j = 0; j < self.thisTableData.length; j++) {
            let flag = true;
            for (let k = 0; k < self.selections.length; k++) {
              if (
                self.thisTableData[j].payLineDetailId ==
                self.selections[k].payLineDetailId
              ) {
                flag = false;
                break;
              }
            }
            if (flag) {
              self.selections.push(self.thisTableData[j]);
              flag = true;
            }
          }
          this.selectStatus = true;
        }
      }
    },
    onSelect(selection, row) {
      const self = this;
      if (self.selections.length > 0) {
        if (self.selections[0].statusName == row.statusName) {
          self.selections.push(row);
          self.selectAllFlag = '3';
          row.checkStatus = true;
        } else {
          for (let i = 0; i < self.thisTableData.length; i++) {
            if (row.payLineDetailId == self.thisTableData[i].payLineDetailId) {
              self.$set(self.thisTableData[i], '_checked', true);
              self.$forceUpdate();
              break;
            }
          }
          setTimeout(() => {
            for (let i = 0; i < self.thisTableData.length; i++) {
              if (
                row.payLineDetailId == self.thisTableData[i].payLineDetailId
              ) {
                self.$set(self.thisTableData[i], '_checked', false);
                self.$Message.info('请选择状态一样的明细行');
                break;
              }
            }
          }, 10);
        }
      } else {
        self.selections.push(row);
        self.selectAllFlag = '3';
        row.checkStatus = true;
      }
    },
    onSelectCannel(selection, row) {
      for (let i = 0; i < this.selections.length; i++) {
        if (this.selections[i].payLineDetailId == row.payLineDetailId) {
          this.selections[i].checkStatus = false;
          this.selections.splice(i, 1);
          break;
        }
      }
      this.selectAllFlag = '3';
    },
    onSelectionChange() {
      const self = this;
      if (self.selectAllFlag != '3') {
        if (this.selectStatus) {
        } else {
          for (let i = self.selections.length - 1; i >= 0; i--) {
            // 同时判断payWayName/companyName/accountName/accountNo/statusName是否一致来区分申请准备明细的分组
            if (
              self.row.payWayName +
                self.row.companyName +
                self.row.companyCode +
                self.row.accountName +
                self.row.accountNo +
                self.row.statusName ==
              self.selections[i].payWayName +
                self.selections[i].companyName +
                self.selections[i].companyCode +
                self.selections[i].accountName +
                self.selections[i].accountNo +
                self.selections[i].statusName
            ) {
              self.selections.splice(i, 1);
            }
          }
        }
      }
      this.selectAllFlag = '2';
      this.selectStatus = false;
    }
  }
};
</script>
