<template>
  <div>
    <el-dialog title="关联" :visible.sync="dialogVisible" width="66%">
      <template>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="list.push({ link_table_name: '',local_key: '',foreign_key: '',link_relation: '' })"></el-button>

        <xy-table
          style="margin-top: 10px;"
          :auths="[]"
          size="small"
          :is-page="false"
          :list="list"
          :table-item="table"
        >

        </xy-table>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible = false"
          >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { realTableShow, realTableIndex, save, show, relationDestroy, update } from "@/api/system/customForm";
import {listparameter} from "@/api/system/dictionary";

export default {
  data() {
    return {
      id: '',
      copyTable: {},
      dialogVisible: false,
      tableName: "",
      localFields: {},
      realTables: [],
      foreignFields: [],
      parameters: [], //数据字典

      list: [],
      table: [
        {
          prop: "local_key",
          label: "关联本地字段",
          customFn: (row) => {
            return (
              <el-select size="mini"
                         value={ row.local_key }
                         on={{
                           ['change']:e => {
                             row.local_key = e
                           }
                         }}>
                {
                  [{field:'id',name:'id'},...this.localFields].map(i => {
                    return (
                      <el-option value={ i.field } label={ i.name }></el-option>
                    )
                  })
                }
              </el-select>
            );
          },
        },
        {
          prop: 'link_table',
          label: '关联表',
          customFn: (row) => {
            return (
              <el-select size="mini"
                         clearable={true}
                         value={row.link_table_name}
                         on={{
                           ['change']:async e => {
                             row.link_table_name = e
                             if (e) {
                               this.foreignFields = await this.getFields(e)
                             }
                           }
                         }}>
                {
                  this.realTables.map(i => {
                    return (
                      <el-option value={i} label={i}></el-option>
                    )
                  })
                }
              </el-select>
            );
          },
        },
        {
          prop: 'parameter_id',
          label: '关联数据字典',
          customFn: (row) => {
            return (
              <el-select size="mini"
                         clearable={true}
                         value={row.parameter_id}
                         on={{
                           ['change']:async e => {
                             row.parameter_id = e
                             if (e) {
                               this.foreignFields = await this.getFields('parameters')
                             }
                           }
                         }}>
                {
                  this.parameters.map(i => {
                    return (
                      <el-option value={i.id} label={i.name}></el-option>
                    )
                  })
                }
              </el-select>
            );
          },
        },
        {
          prop: "foreign_key",
          label: "关联表字段",
          customFn: (row) => {
            return (
              <el-select size="mini"
                         value={row.foreign_key}
                         on={{
                           ['change']:e => {
                             row.foreign_key = e
                           }
                         }}>
                {(() => {
                  let dom = [];
                  for (let key in this.foreignFields) {
                    dom.push(<el-option label={key} value={key}></el-option>);
                  }
                  return dom;
                })()}
              </el-select>
            );
          },
        },
        {
          prop: 'link_relation',
          label: '关联方式',
          customFn: (row) => {
            return (
              <el-select size="mini"
                         value={row.link_relation}
                         on={{
                           ['change']:e => {
                             row.link_relation = e
                           }
                         }}>
                {
                  [
                    { value: 'newHasOne', label: '一对一' },
                    { value: 'newHasMany', label: '一对多' },
                  ].map(i => {
                    return (
                      <el-option value={i.value} label={i.label}></el-option>
                    )
                  })
                }
              </el-select>
            );
          },
        },
        {
          prop: 'operate',
          label: '操作',
          align: 'left',
          customFn:(row, scope) => {
            return [(
              <el-button type='primary'
                         size="mini"
                         style={{
                           'margin-right': '6px'
                         }}
                         on={{
                           ['click']:e => {
                             this.copyTable.relation = this.list
                             save(this.copyTable).then(res => {
                               this.getDetail()
                               update({ id: this.copyTable.id })
                             })
                           }
                         }}>确 定</el-button>
            ),(
              <el-popover width="180"
                          trigger="hover"
                          scopedSlots={{
                            "default": () => {
                              return (
                                <div>
                                  <p style={{'padding-bottom':'10px'}}>确定要删除吗？</p>
                                  <div style={{"text-align":"right","margin":"0"}}>
                                    <el-button size="mini"
                                               type="text"
                                               on={{
                                                 ['click']:e => {
                                                 }
                                               }}>取消</el-button>
                                    <el-button type="primary"
                                               size="mini"
                                               on={{
                                                 ['click']:() => {
                                                   if(row.id){
                                                     relationDestroy({ id: row.id }).then(res => {
                                                       this.getDetail()
                                                       update({ id: this.copyTable.id })
                                                     })
                                                   } else {
                                                     this.list.splice(scope.$index, 1)
                                                   }
                                                 }
                                               }}>确定</el-button>
                                  </div>
                                </div>
                              )
                            },
                            "reference":() => {
                              return (
                                <el-button
                                  type="danger"
                                  size="mini"
                                >
                                  删除
                                </el-button>
                              )
                            }
                          }}>

              </el-popover>
            )]
          }
        }
      ],
    };
  },
  methods: {
    show() {
      this.dialogVisible = true;
    },
    hide() {
      this.dialogVisible = false;
    },
    set(key = [], value = []) {
      if (key instanceof Array) {
        key.forEach((key, index) => {
          this[key] = value[index] ?? "";
        });
      }
      if (typeof key === "string") {
        this[key] = value;
      }
    },

    async getParameters() {
      const res = await listparameter({ page: 1, page_size: 999 });
      this.parameters = res.data;
    },
    async getFields(tableName) {
      const res = await realTableShow({ table_name: tableName });
      console.log(res);
      res['id'] = 'integer';
      return res || {};
    },
    async getRealTables() {
      const res = await realTableIndex();
      this.realTables = res;
    },
    async getDetail() {
      const res = await show({ id: this.copyTable?.id })
      this.localFields = res.fields || []

      this.list = res.relation.map(i => {
        return i
      })
    },
    submit(scope) {
      console.log(scope)
    }
  },
  computed: {},
  watch: {
    async dialogVisible(newVal) {
      if (newVal) {
        //this.localFields = await this.getFields(this.tableName);
        await this.getDetail();
      }
    },
  },
  created() {
    this.getParameters();
    this.getRealTables();
  },
};
</script>

<style scoped lang="scss"></style>
