<template>
  <div :class="[$style.wrapper, $style.sdFormforxmchild]">
    <div v-if="captionvisiable" :class="[$style.caption]">
      {{ label }}
      <div v-if="!readOnly" :class="$style.header">
        <a-button v-if="addbuttonvisiable" type="link" @click="add">
          <a-icon type="plus-circle" :theme="'filled'" />
          添加
        </a-button>
        <a-button
          type="link"
          :disabled="selectColumnsLength === 0"
          @click="remove(selectedRowKeys)"
        >
          <a-icon type="minus-circle" :theme="'filled'" />
          删除
        </a-button>
        <a-button v-if="savebuttonvisiable" type="link" @click="save">
          <a-icon type="check-circle" :theme="'filled'" />
          保存
        </a-button>
      </div>
    </div>
    <sd-table
      v-if="sdtableflag"
      ref="sdtable"
      :show-selection="false"
      size="middle"
      :columns="_columns"
      :width="width"
      sortable
      :data-source="value"
      :show-header="false"
      :row-key="(record, index) => index"
      :pagination="false"
      :row-selection="null"
      :custom-row="
        (record, index) => {
          return {
            on: {
              click: () => {
                edit(index)
              },
            },
          }
        }
      "
      @update:data-source="fnupdate"
    >
      <template
        v-for="(field, index) in fields"
        :slot="'sd_' + field.name"
        slot-scope="text, record, index"
      >
        <slot v-bind="{ field, text, record, value, index }" :name="field.name + '_xm'">
          <sdForm :ref="field.name + '_' + index" :init-values="[field]" :read-only="readOnly">
            <template v-if="!readOnly" v-slot="scope">
              <slot v-bind="{ field, text, record, value, index }" :name="field.name"> </slot>
            </template>
            <template v-if="readOnly">
              {{ getDisplayVaule(field, text) }}
            </template>
          </sdForm>
        </slot>
      </template>
    </sd-table>
    <div :class="$style.loading">
      <a-spin v-if="!sdtableflag" />
    </div>
  </div>
</template>

<script>
import { Modal } from 'ant-design-vue'
import { getComponentSpec } from '@/common/components/sd-form'
import moment from 'moment'
import components from './_import-components/risk-criteria-child-table-import'

// Vue.use(DatePicker)
// Vue.use(TimePicker)
/**
 * 主子表、动态表格字段
 * @displayName XmChildTable 主子表
 */
export default {
  name: 'RiskCriteriaChildTable',
  components: {
    ...components,
    sdForm: () => import('@/common/components/sd-form'),
  },
  model: {
    prop: 'value',
    event: 'change',
  },
  props: {
    /**
     * 字表的值，{key:value}的格式
     */
    value: {
      type: Array,
      default: () => [],
    },
    /**
     * 字表的字段属性
     */
    fields: {
      type: Array,
      default: () => [],
    },
    /**
     * 是否只读
     */
    readOnly: {
      type: Boolean,
      default: false,
    },
    /**
     * 标签名
     */
    label: {
      type: String,
      default: '',
    },
    /**
     * 自定义子表列属性,如[{dataIndex:'shuxingmingzi15',width:'120px'}],8.0.4及以后版本支持
     */
    columns: {
      type: Array,
      default: () => [],
    },
    /**
     * 某行是否可选
     * @since 8.0.11
     */
    showSelection: {
      type: Function,
      default: () => true,
    },
    width: {
      type: Number,
      default: 100,
    },
    datachange: {
      type: Function,
      default: null,
    },
    dzcl: {
      type: Boolean,
      default: false,
    },
    addfun: {
      type: Function,
      default: null,
    },
    captionvisiable: {
      type: Boolean,
      default: true,
    },
    addbuttonvisiable: {
      type: Boolean,
      default: true,
    },
    savebuttonvisiable: {
      type: Boolean,
      default: false,
    },
    fncheckdelete: {
      type: Function,
      default: null,
    },
    // 是否批量提交
    patchSave: {
      type: Boolean,
      default: false,
    },
    selectColumns: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      selectedRowKeys: [],
      visible: false,
      editRecord: this.fields, // 待修改或编辑的记录
      attkeys: {}, // 附件组件的key,行编辑了就修改对应的附件key,强制更新附件列表
      savevisible: true,
      adddataxm: {},
      selectitem: [],
      sjjs: this.getsjsl(),
      ndata: [],
      newfield: [],
      validflag: true,
      sdtableflag: true,
      localLoading: false,
    }
  },
  computed: {
    _columns() {
      const fields = JSON.parse(JSON.stringify(this.fields))
      return fields
        .filter((item) => item.dataType !== 'id')
        .map((item) => {
          const t = {
            dataIndex: item.name,
            key: item.name,
            title: item.caption,
            scopedSlots: { customRender: 'sd_' + item.name },
            width: item.width || '40',
          }
          const column = this.columns.find((c) => c.dataIndex === item.name)
          if (column) Object.assign(t, column)
          return t
        })
        .filter((item) => item.sdHidden !== true)
    },
    selectColumnsLength() {
      return this.selectColumns
    },
  },
  mounted() {
    if (this.datachange) {
      this.datachange()
    }
    if (this.dzcl) {
      this.fields.forEach((item) => {
        if (item.name === 'userType') {
          let index = item.attr.selectListItem.findIndex((item) => item.label === '项目组长')
          item.attr.selectListItem.splice(index, 1)
          index = item.attr.selectListItem.findIndex((item) => item.label === '项目负责人')
          item.attr.selectListItem.splice(index, 1)
          this.selectitem = item.attr.selectListItem
        }
      })
    }
  },
  destroyed() {
    const data = this.value || [] // 兼容初始值是null的情况
    const index = data.findIndex((item) => item.editable === true)
    if (index !== -1) {
      this.optbuttonClick('delete', [], index)
    }
  },
  methods: {
    fnupdate(data) {
      this.sdtableflag = false
      const newData = [...data]
      this.value.splice(0)
      newData.forEach((item) => {
        this.value.push(item)
      })
      setTimeout(() => {
        this.sdtableflag = true
      }, 0)
      this.$emit('change', this.value)
    },
    moment,
    getsjsl() {
      let index
      this.fields.forEach((f) => {
        if (f.sdHidden === true) {
          index = index + 1
        }
      })
      return index
    },
    fngetfield(field, value) {
      const editRecord = [field]
      editRecord.forEach((item) => {
        // 把值放到字段信息fields里
        item.value = value[item.name]
        if (item.attr.controlType === 'DictType') {
          if (item.attr.selectListItem.find((t) => t.value === item.value) !== undefined) {
            item.attr.displayValue = item.attr.selectListItem.find(
              (t) => t.value === item.value
            ).label
          }
        }
      })
      return editRecord
    },
    getDisplayVaule(field, text) {
      if (getComponentSpec(field).getDisplayValue) {
        if (typeof text !== 'undefined' && text !== null) {
          const value = getComponentSpec(field).parseBackendValue?.(text) || text
          return getComponentSpec(field).getDisplayValue(value)
        } else {
          return ''
        }
      }
      return text
    },
    changolddata() {
      const h = new Promise((resolve) => {
        if (this.value !== null) {
          if (this.value.length > 0) {
            this.value.forEach((d, index) => {
              if (d.mainId === 0) {
                // 获取该行数据
                d.mainId = Math.random()
              }
              this.savetableh(index, null).then((r) => {
                if (index === this.value.length - 1) {
                  resolve(true)
                }
              })
            })
          } else {
            resolve(false)
          }
        } else {
          resolve(true)
        }
      })
      return h
    },
    savetableh(i, field) {
      // 保存最新增的行
      const data = this.value || [] // 兼容初始值是null的情况
      const value = data[i]
      let fields = this.fields
      if (field !== null) {
        fields = [field]
      }
      const savef = new Promise((resolve) => {
        fields.forEach((item, index) => {
          const refname = item.name
          const dataType = item.dataType
          if (this.$refs[refname + '_' + i]) {
            if (dataType === 'attachment') {
            } else if (
              typeof this.$refs[refname + '_' + i][0].model[refname] === 'object' &&
              dataType !== 'date'
            ) {
              if (this.$refs[refname + '_' + i][0].model[refname] !== undefined) {
                value[item.name] = JSON.stringify(this.$refs[refname + '_' + i][0].model[refname])
              }
            } else if (dataType === 'date') {
              if (this.$refs[refname + '_' + i][0].model[refname] !== undefined) {
                value[item.name] = this.$refs[refname + '_' + i][0].getFieldValue(refname).valueOf()
              }
            } else {
              if (this.dzcl && refname === 'userType') {
                if (value[item.name] !== '04' && value[item.name] !== '05') {
                  this.$refs[refname + '_' + i][0].setFieldValue(refname, value[item.name])
                }
              } else {
                if (this.$refs[refname + '_' + i][0].model[refname] !== undefined) {
                  value[item.name] = this.$refs[refname + '_' + i][0].getFieldValue(refname)
                }
              }
            }
          }
        })
        // 一行数据已存储
        data[i] = value
        this.value = data
        if (!this.patchSave) {
          this.$emit('saved', data)
        }
        // this.$emit('change', data)
        resolve(true)
        // 打开结束时间
        if (field && field.name === 'joinStartTime') {
          document
            .querySelector("[nodename='joinEndTime_" + i + "'] .ant-calendar-picker-input")
            .click()
        }
      })
      return savef
    },
    add() {
      this.$emit('addData')
    },
    edit(index) {},
    setvalid() {
      this.value.forEach((h, index) => {
        // if (this.validflag) {
        const value = {}
        this.fields.forEach((item, fi) => {
          const refname = item.name
          const dataType = item.dataType
          if (this.$refs[refname + '_' + index]) {
            this.$refs[refname + '_' + index][0].validateFields().then((res) => {})
          }
        })
      })
    },
    valid() {
      this.validflag = true
      const data = this.value || [] // 兼容初始值是null的情况
      const valid = new Promise((resolve) => {
        // 轮询所有行数据
        if (data.length === 0) {
          resolve(true)
        } else {
          data.forEach((h, index) => {
            this.fields.forEach((item, fi) => {
              const refname = item.name
              if (this.$refs[refname + '_' + index]) {
                this.$refs[refname + '_' + index][0]
                  .validateFields()
                  .then((res) => {
                    if (!res) {
                      this.validflag = false
                    } else {
                      if (index === data.length - 1 && fi === this.fields.length - 1) {
                        setTimeout(() => {
                          if (this.validflag) {
                            resolve(true)
                          } else {
                            resolve(false)
                          }
                        }, 1000)
                      }
                    }
                  })
                  .catch(() => {
                    this.validflag = false
                  })
              } else {
                if (index === data.length - 1 && fi === this.fields.length - 1) {
                  setTimeout(() => {
                    if (this.validflag) {
                      resolve(true)
                    } else {
                      resolve(false)
                    }
                  }, 1000)
                }
              }
            })
          })
        }
      })
      return valid
    },
    save() {
      if (this.readOnly || !this.visible) {
        // 判断visable为false时，modal没有是为了防止快速重复点击确定
        this.visible = false
      }
      this.changolddata().then((res) => {})
      const save = new Promise((resolve, reject) => {
        const data = this.value || [] // 兼容初始值是null的情况
        // 轮询所有行数据
        if (data.length === 0) {
          resolve(false)
        } else {
          let canSubmit = true
          data.forEach((h, index) => {
            const value = {}
            this.fields.forEach((item, fi) => {
              const refname = item.name
              const dataType = item.dataType
              if (this.$refs[refname + '_' + index]) {
                return this.$refs[refname + '_' + index][0]
                  .validateFields()
                  .then(() => {
                    if (index === data.length - 1 && fi === this.fields.length - 1) {
                      setTimeout(() => {
                        if (canSubmit) {
                          resolve(true)
                          this.$emit('change', this.value)
                        } else {
                          resolve(false)
                        }
                      }, 0)
                    }
                  })
                  .catch(() => {
                    canSubmit = false
                  })
              }
            })
            if (index === data.length - 1) {
              // resolve(true)
              if (canSubmit) {
                // this.$emit('change', this.value)
                // resolve(true)
              }
            }
          })
        }
      })
      return save
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
      this.$emit('onSelectChange', this.selectedRowKeys)
    },
    remove(keys) {
      this.$emit('deleteData')
    },
    optbuttonClick(val, record, i) {
      let value = {}
      const data = this.value || [] // 兼容初始值是null的情况
      const adddata = this.adddataxm || {}
      let index = 0
      const qqcs = this._columns.length - 2
      const editrow = data.find((c) => c.editable === true)
      switch (val) {
        case 'save':
          value = data[i]
          this.fields.forEach((item) => {
            const refname = item.name
            const dataType = item.dataType
            if (this.$refs[refname]) {
              this.$refs[refname][0].validateFields().then(() => {
                this.$refs[refname][0].getBackendValues().forEach((item) => {
                  if (item.name === refname) {
                    if (dataType === 'attachment') {
                      if (adddata[refname] !== undefined) {
                        var obj = JSON.parse(adddata[refname])
                        value[item.name] = '{"value":"' + obj.value + '"}'
                      } else {
                        value[item.name] = item.value
                      }
                    } else {
                      value[item.name] = item.value
                    }
                  }
                })
                index = index + 1
                if (index === qqcs) {
                  this.attkeys[0] = Math.random()
                  value.editable = false
                  data.splice(i, 1)
                  data.splice(i, 0, value)
                  this.$emit('change', data)
                  this.value = data
                }
              })
            }
          })
          this.adddataxm = {}
          // event.stopPropagation()
          break
        case 'delete':
          if (this.fncheckdelete !== null) {
            if (this.fncheckdelete(data, i)) {
              data.splice(i, 1)
              this.$emit('change', data)
              this.adddataxm = {}
            } else {
              Modal.warning({
                title: '提示',
                content: '选择的子表数据不允许删除，请检查!',
              })
              return false
            }
          } else {
            data.splice(i, 1)
            this.$emit('change', data)
            this.adddataxm = {}
          }
          this.value = data
          break
        case 'edit':
          // 判断当前动态表格中是否有已打开编辑的行，如果有则需要保存后才能再新增
          if (editrow !== undefined) {
            Modal.warning({
              title: '提示',
              content: '请先保存动态表格中内容!',
            })
            return false
          }
          if (data[i].editable === undefined || data[i].editable === false) {
            data[i].editable = true
            const value = data[i]
            data.splice(i, 1)
            data.splice(i, 0, value)
            this.$emit('change', data)
            this.editRecord = JSON.parse(JSON.stringify(this.fields))
            this.editRecord[0].editable = true
            this.editRecord.forEach((item) => {
              // 把值放到字段信息fields里
              item.value = value[item.name]
              if (item.attr.controlType === 'DictType') {
                if (item.attr.selectListItem.find((t) => t.value === item.value) !== undefined) {
                  item.attr.displayValue = item.attr.selectListItem.find(
                    (t) => t.value === item.value
                  ).label
                }
              }
            })
            this.adddataxm = value
          }
          break
      }
    },
    fnsettablesize() {
      const obj = this.$refs.sdtable
      obj.columnInfos.forEach((col) => {
        col.width = col.defaultWidth
        col.show = col.defaultShow
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
@use "@/common/components/sd-web-print.scss" as print;
.header {
  position: absolute;
  top: 0;
  right: 0;
  :global .ant-input-search {
    width: 200px;
  }
  :global .ant-btn {
    margin: 5px;
  }
}
.caption {
  // position: relative;
  position: absolute;
  width: 100%;
  min-height: 40px;
  margin: 3px 0;
  text-align: center;
}
.wrapper {
  :global(.ant-table-tbody) {
    .clickable-cell {
      color: $primary-color;
      cursor: pointer;
      &:hover {
        color: $primary-5;
      }
      &:active {
        color: $primary-7;
      }
    }
  }
}

// 打印状态下 子表上选择列的按钮
@include print.wrapper-for-printer {
  .wrapper {
    :global(.ant-table-thead .anticon) {
      display: none;
    }
  }
}
.operatecol {
  // display: flex;
  // flex-wrap: wrap;
  justify-content: flex-end;
  width: 100px;
  :global(.ant-btn-sm) {
    padding: 0 0;
  }
  :global(.menu_sd-table-header_common) {
    display: none;
  }
}
.sdFormforxmchild {
  :global(.ant-upload.ant-upload-drag p.ant-upload-drag-icon) {
    margin-bottom: 0;
  }
  :global(.ant-upload-text) {
    display: none !important;
  }
  :global(.ant-upload.ant-upload-drag .ant-upload) {
    padding: 0 0;
  }
  :global(.ant-form-item) {
    margin-bottom: 6px;
  }
  :global(.actionlist_sd-attachment_common > span) {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  :global(.actionlist_sd-attachment_common > span :hover) {
    white-space: normal;
    // overflow: auto;
  }
  :global(.ant-upload.ant-upload-drag) {
    text-align: left;
    background: none;
    border: none;
  }
  :global(.ant-upload.ant-upload-drag p.ant-upload-drag-icon .anticon) {
    font-size: 28px;
  }
  :global(.form_sd-form_common > .ant-form-item > .ant-form-item-control-wrapper) {
    width: 100%;
  }
  .loading {
    position: fixed;
    top: 310px;
    left: 50%;
    text-align: center;
  }
  :global(.ant-calendar-cell) {
    border: none !important;
  }
}
</style>
