<template>
  <div>
    <el-page-header
      :content="
        $route.meta.title + ' - ' +
        (detail.name || detail.mingcheng || detail.no || detail.bianhao || ' ')
      "
      style="
        padding: 1em;
        font-size: 1em;
        background: #fff;
        margin: 1.67em 0;
        box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
        border-radius: 5px;
      "
      @back="$router.back()"
    >
    </el-page-header>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <div class="el-descriptions__header el-descriptions__title">
            基本信息
          </div>
          <el-descriptions
            border
            size="small"
            :column="2"
            :label-style="{ 'font-weight': '600' }"
          >
            <el-descriptions-item
              v-for="item in showFields"
              :label="item.name"
              v-if="!['file', 'picture'].find((j) => j === item.field)"
            >
              <template v-if="item.edit_input === 'richtext'">
                <div v-html="detail[item.field]"></div>
              </template>
              <template v-else>
                {{ contentFormat(item)
                }}
              </template>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card v-for="item in linkTableList">
          <div class="el-descriptions__header el-descriptions__title">
            {{ item.title }}
          </div>
          <xy-table size="mini" :height="300" :is-page="false" :list="item.value" :table-item="item.field"></xy-table>
        </el-card>
      </el-col>
    </el-row>

    <el-backtop></el-backtop>

    <Modal
      :width="76"
      transfer
      :z-index="6000"
      v-model="showModal"
      :footer-hide="true"
      title="预览"
    >
      <template>
        <iframe
          style="width: 100%; height: 57vh"
          :src="codeUri"
          border="0"
        ></iframe>
      </template>
    </Modal>
  </div>
</template>

<script>
import { show, index } from "@/api/system/baseForm";
import { show as formShow, index as customFormIndex } from "@/api/system/customForm";
import { getparameter } from "@/api/system/dictionary";
import { listdept } from "@/api/system/department";
import { download } from "@/utils/downloadRequest";
export default {
  name: "detail",
  data() {
    return {
      showModal:false,
      codeUri: "",

      detail: {},
      fields: [],
      relation: [],
      customForm: {
        customFormId: "",
        tableName: "",
      },

      allTables: [],
      linkTableList: [],
    };
  },
  methods: {
    open(url) {
      this.codeUri = `http://view.ali251.langye.net:8012/onlinePreview?url=${encodeURIComponent(
        new Buffer(url).toString("base64")
      )}`;

      this.showModal = true;
    },

    down(e) {
      download(e.url, "get", {}, e.original_name);
    },

    getAllTables () {
      customFormIndex({
        page: 1,
        page_size: 999
      }).then(res => {
        this.allTables = res.data
      })
    },

    getLinkTableList () {
      let relationFields = this.fields.filter(field => (field._relations?.link_relation === 'newHasMany' || field._relations?.link_relation === 'hasMany'));
      for (let i = 0;i < relationFields.length;i++) {
        let item = relationFields[i]
        let table_id = this.allTables.find(table => table.table_name === item._relations.link_table_name)?.id
        let promiseAll = [
          index({
            table_name: item._relations.link_table_name,
            page: 1,
            page_size: 999,
            filter: [
              {
                key: item._relations.foreign_key,
                op: 'eq',
                value: this.$route.params.id
              }
            ]
          }),
          formShow({
            id: table_id
          })
        ];

        Promise.all(promiseAll).then(res => {
          if (item.edit_input !== 'files') {
            let dataTable = this.allTables.find(t => t.table_name === res[1].relation[0]?.link_table_name);
            if (dataTable) {
              formShow({ id: dataTable?.id }).then(res1 => {
                this.linkTableList.push({
                  value: res[0].data?.map(o => o[res[1]?.relation[0]?.link_with_name]),
                  field: this.formatColumn(res1),
                  title: res[1]?.name
                })
              })
            } else {
              this.linkTableList.push({
                value: this.detail[item?._relations?.link_with_name],
                field: this.formatColumn(res[1]),
                title: res[1]?.name
              })
            }
          } else {
            this.linkTableList.push({
              value: res[0].data?.map(o => o[res[1]?.relation[0]?.link_with_name]),
              field: [
                {
                  type: 'index',
                  label: '序号',
                  width: 50
                },
                {
                  prop: 'original_name',
                  label: '文件名'
                },
                {
                  label: '操作',
                  width: 100,
                  customFn:row => {
                    return (
                      <div>
                        <el-button
                          type="primary"
                          icon="el-icon-download"
                          circle
                          size="mini"
                          on={{
                            ['click']:_ => this.down(row)
                          }}
                        ></el-button>
                        <el-button
                          type="primary"
                          icon="el-icon-search"
                          circle
                          size="mini"
                          on={{
                            ['click']:_ => this.open(row.url)
                          }}
                        ></el-button>
                      </div>
                    )
                  }
                }
              ],
              title: res[1]?.name
            })
          }
        })
      }
    },

    formatColumn (info) {
      let table = [];
      //字段处理
      //初始表白名单
      let baseTable = new Map([
        ['departments', async () => {
          const res = await listdept()
          return res
        }],
        ['admins',[]]
      ])
      let { fields, relation } = info;
      let fieldRes = fields.sort((a,b) => a.sort - b.sort)
      if (
        !fields ||
        !relation ||
        !fields instanceof Array ||
        !relation instanceof Array
      ) {
        throw new Error("fields或relation格式错误");
      }
      fieldRes?.forEach((i, index) => {
        i._relations = relation.find((j) => j.custom_form_field === i.field);
        if (i.select_item && typeof i.select_item === 'object') {
          let keys = Object.keys(i.select_item)
          i._params = keys.map(key => {
            return {
              key,
              value: i.select_item[key]
            }
          })
        }
        if (i.edit_input === 'file' || i.edit_input === 'files') {
          return
        }
        if (i._relations) {
          if (baseTable.get(i._relations.link_table_name)) {
            baseTable.get(i._relations.link_table_name)().then(res => i._params = res)
          } else {
            i._params = i._relations.parameter_id
              ? getparameter({ id: i._relations.parameter_id },false).then((res) => {
                i._params = res.detail;
              })
              : this.index({
                table_name: i._relations.link_table_name,
                page: 1,
                page_size: 9999,
              }).then((res) => {
                i._params = res.data;
              });
          }
        }
      });
      fields
        ?.filter((i) => i.list_show)
        .forEach((i) => {
          if (i._relations) return
          let linkOb = {};

          if (i.edit_input === "richtext") {
            linkOb.customFn = (row) => {
              return (
                <div
                  style={{ "max-height": "55px","overflow": "scroll" }}
                  domPropsInnerHTML={row[i.field]}
                ></div>
              );
            };
          }
          if (
            i.select_item &&
            typeof i.select_item === "object" &&
            !(i.select_item instanceof Array)
          ) {
            let keys = Object.keys(i.select_item);
            linkOb.customFn = (row) => {
              let paramMap = new Map();
              keys.forEach((key) => {
                paramMap.set(i.select_item[key], key);
              });

              return <span>{paramMap.get(row[i.field]?.toString())}</span>;
            };
          }
          if (i._relations) {
            let { link_relation, foreign_key, link_with_name } = i._relations;
            if (link_relation === "newHasOne" || link_relation === "hasOne") {
              linkOb.customFn = (row) => {
                if (i.edit_input === "file") {
                  return (
                    <a
                      download={row[link_with_name]?.original_name}
                      href={row[link_with_name]?.url}
                    >
                      {row[link_with_name]?.original_name}
                    </a>
                  );
                } else {
                  return (
                    <span>
                      {row[link_with_name]?.name ||
                        row[link_with_name]?.no ||
                        row[link_with_name]?.value}
                    </span>
                  );
                }
              };
            }

            if (link_relation === "hasMany" || link_relation === "newHasMany") {
              linkOb.customFn = (row) => {
                if (i.edit_input === "files") {
                  return (
                    <div style="display: flex;flex-direction: column;">
                      {row[link_with_name]?.map((o) => (
                        <a>
                          { o?.original_name || o?.name }
                        </a>
                      ))}
                    </div>
                  )
                } else {
                  return (
                    <div>
                      {row[link_with_name]?.map((o) => (
                        <p>
                          {o?.name ||
                            o?.no ||
                            o?.value ||
                            o?.biaoti ||
                            o?.mingcheng}
                        </p>
                      ))}
                    </div>
                  );
                }
              };
            }
          }
          table.push(
            Object.assign(
              {
                prop: i.field,
                label: i.name,
                width: i.width,
                fixed: i.is_fixed,
              },
              linkOb
            )
          );
        });
      table.unshift({
        type: "index",
        width: 60,
        label: "序号",
      });

      return table;
    },

    async getFields() {
      this.getAllTables();

      if (this.$route.meta.params?.custom_form) {
        let decode = decodeURIComponent(this.$route.meta.params?.custom_form);
        try {
          let custom_form = JSON.parse(decode);
          this.customForm.customFormId = custom_form.custom_form_id;
          this.customForm.tableName = custom_form.table_name;
        } catch (err) {
          console.warn(err);
        }
      }

      const res = await formShow({ id: this.customForm.customFormId }, false);
      this.fields = res.fields.sort((a, b) => a.sort - b.sort);
      this.relation = res.relation;

      //字段处理
      //初始表白名单
      let baseTable = new Map([
        [
          "departments",
          async () => {
            const res = await listdept();
            return res;
          },
        ],
        ["admins", []],
      ]);
      let { fields, relation } = this;
      if (
        !fields ||
        !relation ||
        !fields instanceof Array ||
        !relation instanceof Array
      ) {
        throw new Error("fields或relation格式错误");
      }
      fields
        .sort((a, b) => a.sort - b.sort)
        .forEach((i) => {
          i._relations = relation.find(
            (j) => j.custom_form_field === i.field
          );
          if (i.select_item && typeof i.select_item === "object") {
            let keys = Object.keys(i.select_item);
            i._params = keys.map((key) => {
              return {
                key,
                value: /^\d*$/.test(i.select_item[key])
                  ? Number(i.select_item[key])
                  : i.select_item[key],
              };
            });
          }
          if (i.edit_input === "file" || i.edit_input === "files") {
            return;
          }
          if (i._relations) {
            if (baseTable.get(i._relations.link_table_name)) {
              baseTable
                .get(i._relations.link_table_name)()
                .then((res) => {
                  i._params = res.data;
                });
            } else {
              // i._params = i._relations.parameter_id
              //   ? getparameter({ id: i._relations.parameter_id }, false).then(
              //     (res) => {
              //       i._params = res.detail;
              //     }
              //   )
              //   : this.index({
              //     table_name: i._relations.link_table_name,
              //     page: 1,
              //     page_size: 9999,
              //   }).then((res) => {
              //     i._params = res.data;
              //   });
            }
          }
        });

      const detail = await show({
        id: this.$route.params.id,
        table_name: this.customForm.tableName,
      });
      this.detail = detail;
    },

  },

  computed: {
    showFields () {
      console.log(this.fields)
      return this.fields.filter(field => (!field._relations || field._relations.link_relation === 'hasOne' || field._relations.link_relation === 'newHasOne'))
    },
    contentFormat() {
      return function (i) {
        let { _relations } = i;
        if (_relations && _relations.link_table_name) {
          if (
            _relations.link_relation === "hasOne" ||
            _relations.link_relation === "newHasOne"
          ) {
            return (
              this.detail[_relations.link_with_name]?.original_name ||
              this.detail[_relations.link_with_name]?.name ||
              this.detail[_relations.link_with_name]?.no ||
              this.detail[_relations.link_with_name]?.value ||
              this.detail[_relations.link_with_name]?.mingcheng
            );
          }

          return;
        }
        if (i._params && i._params.length > 0) {
          return i._params.find((j) => j.value == this.detail[i.field])?.key;
        }

        return this.detail[i.field];
      };
    },
  },
  created() {
    this.getFields().then(_ => {
      this.getLinkTableList()
    })
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-card {
  margin-bottom: 20px;
}
::v-deep .el-empty__image {
  width: 120px;
}

a {
  color: red;
  text-decoration: none;
  transition: all 0.2s;
}

a:hover {
  color: red;
  text-decoration: underline;
}

.el-descriptions__title {

  position: relative;
  padding-left: 14px;

  &::before {
    content: '';
    width: 4px;
    background: linear-gradient(to bottom,rgb(57, 129, 199), rgba(118, 148, 183, 0.7));

    position: absolute;
    left: 0;
    top: 2px;
    bottom: 2px;
  }
}
</style>
