<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="findtable" type="link" :class="$style.batchselect" @click="creatnewfind">
          <a-icon type="plus-circle" :theme="'filled'" />
          添加
        </a-button>
        <a-button
          v-if="evidencetable"
          type="link"
          :class="$style.btnmuban"
          icon="sd-plus-square"
          @click="createvidence"
          >选择
        </a-button>
        <a-button v-if="addbuttonvisiable" type="link" @click="add">
          <a-icon type="plus-circle" :theme="'filled'" />
          添加
        </a-button>
        <a-button
          v-if="findtable"
          type="link"
          :disabled="selectedRowKeys.length === 0"
          @click="deletefindremove(selectedRowKeys)"
        >
          <a-icon type="minus-circle" :theme="'filled'" />
          删除
        </a-button>
        <a-button
          v-if="!findtable"
          type="link"
          :disabled="selectedRowKeys.length === 0"
          @click="remove(selectedRowKeys)"
          ><a-icon type="minus-circle" :theme="'filled'" />
          删除
        </a-button>
        <AuditAdvancedImport
          :v-if="true"
          :config-id="'41'"
          :import-fun="ImportFun"
        ></AuditAdvancedImport>
      </div>
    </div>
    <sd-table
      size="middle"
      :columns="_columns"
      :width="width"
      sortable
      :data-source="value"
      :row-key="(record, index) => index"
      :pagination="false"
      :row-selection="
        readOnly
          ? null
          : {
              getCheckboxProps(record) {
                return {
                  props: { disabled: !showSelection(record) },
                }
              },
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
            }
      "
      :custom-row="
        (record, index) => {
          return {
            on: {
              click: () => {
                edit(index)
              },
            },
          }
        }
      "
      @update:data-source="($event) => $emit('change', $event)"
    >
      <div slot="sd_opt" slot-scope="text, record, index" :class="$style.operatecol">
        <span v-if="value[index].editable">
          <a-button
            v-for="(bt, indexbt) in buttonsfortable"
            :key="indexbt"
            type="link"
            size="small"
            @click="optbuttonClick(bt.id, record, index)"
            >{{ bt.label }}
          </a-button> </span
        ><span v-else>
          <a-button
            v-for="(bt, indexbt) in buttonssavefortable"
            :key="indexbt"
            type="link"
            size="small"
            @click="optbuttonClick(bt.id, record, index)"
            >{{ bt.label }}
          </a-button>
        </span>
      </div>
      <div slot="islink" slot-scope="text, record">
        <a :title="text" @click="rowClick(record)">{{ text }}</a>
      </div>
      <div slot="suggestionType" slot-scope="text, record">
        {{
          fields.filter((item) => item.name === 'suggestionType').length > 0
            ? fields
                .filter((item) => item.name === 'suggestionType')[0]
                .attr.selectListItem.filter((item) => item.value === text)[0].label
            : text
        }}
      </div>
    </sd-table>
  </div>
</template>

<script>
import { Modal } from 'ant-design-vue'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import { getComponentSpec } from '@/common/components/sd-form'
import moment from 'moment'
import AuditAdvancedImport from '../../../components/audit-advanced-import'
import components from './_import-components/xm-paper-child-table-import'

// Vue.use(DatePicker)
// Vue.use(TimePicker)
/**
 * 主子表、动态表格字段
 * @displayName XmChildTable 主子表
 */
export default {
  name: 'XmPaperChildTable',
  components: {
    ...components,
    AuditAdvancedImport,
  },
  model: {
    prop: 'value',
    event: 'change',
  },

  props: {
    mode: {
      type: String,
      default: '',
    },
    projectId: {
      type: String,
      default: '',
    },
    /**
     * 字表的值，{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: false,
    },
    creatnewfind: {
      type: Function,
      default: null,
    },
    findtable: {
      type: Boolean,
      default: false,
    },
    createvidence: {
      type: Function,
      default: null,
    },
    evidencetable: {
      type: Boolean,
      default: false,
    },
    deletefind: {
      type: Function,
      default: null,
    },
  },
  data() {
    return {
      selectedRowKeys: [],
      visible: false,
      editRecord: [], // 待修改或编辑的记录
      attkeys: {}, // 附件组件的key,行编辑了就修改对应的附件key,强制更新附件列表
      savevisible: true,
      adddataxm: {},
    }
  },
  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 },
            editable: false,
            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)
    },
  },
  mounted() {
    if (this.datachange) {
      this.datachange()
    }
  },
  destroyed() {
    const data = this.value || [] // 兼容初始值是null的情况
    const index = data.findIndex((item) => item.editable === true)
    if (index !== -1) {
      this.optbuttonClick('delete', [], index)
    }
  },
  methods: {
    moment,
    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
    },
    add() {
      this.action = 'add'
      const data = this.value || [] // 兼容初始值是null的情况
      // 判断当前动态表格中是否有已打开编辑的行，如果有则需要保存后才能再新增
      const editrow = data.find((c) => c.editable === true)
      if (editrow !== undefined) {
        Modal.warning({
          title: '提示',
          content: '请先保存动态表格中内容！!',
        })
      } else {
        this.editRecord = this.fields
        const attachobj = this.fields.find((obj) => obj.dataType === 'attachment')
        const d1 = { mainId: 0, editable: true }
        if (attachobj !== undefined) {
          d1[attachobj.name] =
            '{"value":"' + Math.round(Math.random() * 100000000000000000).toString() + '"}'
        }
        if (this.addfun) {
          this.addfun(d1).then((res) => {
            data.push(res)
            this.adddataxm = d1
            this.$emit('change', data)
          })
        } else {
          data.push(d1)
          this.adddataxm = d1
          this.$emit('change', data)
        }
      }
    },
    edit(index) {
      // const data = this.value || [] // 兼容初始值是null的情况
      // if (data[index].editable === undefined) {
      //   this.optbuttonClick(event, 'edit', [], index)
      // }
    },
    save() {
      if (this.readOnly || !this.visible) {
        // 判断visable为false时，modal没有是为了防止快速重复点击确定
        this.visible = false
      }
      this.$refs.form.validateFields().then(() => {
        const value = {}
        this.$refs.form.getBackendValues().forEach((item) => {
          value[item.name] = item.value
        })
        const data = this.value || [] // 兼容初始值是null的情况
        if (this.action === 'add') {
          // 新增
          data.push(value)
        }
        if (!isNaN(this.action)) {
          // 修改
          this.attkeys[this.action] = Math.random()
          data[this.action] = value
        }
        /**
         * 动态表格值变化时触发
         * @property {Object} data 子表的值
         */
        this.$emit('change', [...data])
        this.visible = false
      })
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    remove(keys) {
      // 用的序号作key，从大往小删，防止串了
      const removeKeys = keys.sort((a, b) => b - a)
      removeKeys.forEach((key) => {
        this.value.splice(key, 1)
      })
      this.selectedRowKeys = []
      this.$emit('change', this.value)
    },
    deletefindremove(keys) {
      // 用的序号作key，从大往小删，防止串了
      const removeKeys = keys.sort((a, b) => b - a)
      const valueid = []
      removeKeys.forEach((key) => {
        valueid.push(this.value[key].id)
        this.value.splice(key, 1)
      })
      this.selectedRowKeys = []
      this.$emit('change', this.value)
      this.deletefind(valueid)
    },
    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.adddataxm = {}
          // event.stopPropagation()
          break
        case 'delete':
          data.splice(i, 1)
          this.$emit('change', data)
          this.adddataxm = {}
          break
        case 'edit':
          // 判断当前动态表格中是否有已打开编辑的行，如果有则需要保存后才能再新增
          if (editrow !== undefined) {
            Modal.warning({
              title: '提示',
              content: '请先保存动态表格中内容!',
            })
            return false
          }
          if (data[i].editable === undefined) {
            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
      }
    },
    savesdform() {
      console.log('保存')
    },
    ImportFun(params) {
      params.projectId = this.projectId

      return params
    },
    rowClick(record) {
      const url = '/audit-externalProject-find-form?record=' + record.id + '&mode=' + this.mode // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.refresh()
        }
      })
    },
  },
}
</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: 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%;
  }
}
</style>
