<template>
  <div>
    <Input
      type="text"
      :size="size"
      readonly
      :clearable="!readonly"
      v-model="selected"
      :style="{ width: controlWidth == null ? null : controlWidth + 'px' }"
      @on-focus="dialogSelectOpen()"
      @on-clear="dialogSelectRemove()"
    >
      <template #prepend>
        <Button :size="size" custom-icon="fa fa-search" @click="dialogSelectOpen()"></Button>
      </template>
    </Input>
  </div>
</template>
<script>
  import mixinPage from '../../mixins/page';
  import { mapActions } from 'vuex';
  import modelApi from '../../api/model';
  import customModelApi from '../../api/customModel';
  import dataSourceApi from '../../api/dataSource';

  /**
   * @displayName dialog-select 弹出选择
   */
  export default {
    mixins: [mixinPage],
    data() {
      return {
        //changed: false,
        selected: null,
        selectedData: null,
        dialogTable: null
      };
    },
    props: {
      /**
       * @model
       */
      modelValue: {
        type: String
      },
      /**
       * 原始数据
       */
      rawData: {
        type: Object
      },
      /**
       * 字段代码
       */
      columnCode: {
        type: String
      },
      /**
       * 数据源
       */
      source: {
        type: String
      },
      /**
       * 大小
       * @values small, default, large
       */
      size: {
        type: String
      },
      /**
       * 数据源数据列名
       */
      sourceDataCode: {
        type: String
      },
      /**
       * 数据源显示列名
       */
      sourceDisplayCode: {
        type: String
      },
      /**
       * 参数
       */
      param: {
        type: Object,
        default: () => {
          return {};
        }
      },
      /**
       * 只读
       */
      readonly: {
        type: Boolean,
        default: false
      },
      /**
       * 控件宽度
       */
      controlWidth: {
        type: Number
      },
      /**
       * 能否多选
       */
      multi: {
        type: Boolean,
        default: false
      }
    },
    computed: {},
    watch: {
      modelValue() {
        this.showSelected();

        //this.changed = false;
      }
    },
    mounted() {
      this.showSelected();
    },
    methods: {
      ...mapActions('admin/dataView', { loadDataView: 'load' }),
      // 显示选择项
      showSelected() {
        // 处理空值情况
        if (this.modelValue == null) {
          this.selected = null;
          this.selectedData = null;
          return;
        }

        // 多选模式处理
        if (this.multi) {
          // 验证是否为有效JSON格式
          if (!this.isJSON(this.modelValue)) {
            this.selected = null;
            this.selectedData = null;
            return;
          }

          // 构建查询过滤器
          let filter = {
            page: 1,
            per: 999
          };
          filter[this.sourceDataCode] = JSON.parse(this.modelValue).join(',');

          for (let key in this.param) {
            filter[key] = this.param[key];
          }

          // 加载数据视图并查询
          this.loadDataView(this.source).then(async view => {
            if (view.dataView.isCustom) {
              // 自定义模型查询
              let res = await customModelApi.query(view.dataView.model, filter, [this.sourceDataCode, this.sourceDisplayCode]);
              if (res.data.length > 0) {
                this.selected = res.data
                  .map(item => {
                    return this.parseData(item, this.sourceDisplayCode);
                  })
                  .join(',');

                this.selectedData = res.data;
              }
            } else if (view.dataView.isDataSource) {
              // 数据源查询
              let res = await dataSourceApi.query(view.dataView.dataSource, filter);
              if (res.table.length > 0) {
                this.selected = res.table
                  .map(item => {
                    return this.parseData(item, this.sourceDisplayCode);
                  })
                  .join(',');
                this.selectedData = res.table;
              }
            } else {
              // 普通模型查询
              let res = await modelApi.query(view.dataView.model, filter, [this.sourceDataCode, this.sourceDisplayCode]);
              if (res.data.length > 0) {
                this.selected = res.data
                  .map(item => {
                    return this.parseData(item, this.sourceDisplayCode);
                  })
                  .join(',');

                this.selectedData = res.data;
              }
            }
          });
        } else {
          // 单选模式处理
          if (this.rawData && this.columnCode.endsWith('ID')) {
            // 从原始数据中获取模型信息
            let model = this.parseData(this.rawData, this.columnCode.substring(0, this.columnCode.length - 2));

            if (model != null) {
              let code;

              if (this.sourceDataCode == 'id') {
                code = this.sourceDisplayCode;
              } else if (this.sourceDataCode.endsWith('ID')) {
                let pre = this.sourceDataCode.substring(0, this.sourceDataCode.length - 2) + '.';

                if (this.sourceDisplayCode.startsWith(pre)) {
                  code = this.sourceDisplayCode.substring(pre.length);
                }
              }

              if (code) {
                let selected = this.parseData(model, code);

                if (selected) {
                  this.selected = selected;
                  return;
                }
              }
            }
          }

          // 构建单选查询过滤器
          let filter = {
            page: 1,
            per: 1
          };
          filter[this.sourceDataCode] = this.modelValue;

          for (let key in this.param) {
            filter[key] = this.param[key];
          }

          // 加载数据视图并查询
          this.loadDataView(this.source).then(async view => {
            if (view.dataView.isCustom) {
              // 自定义模型查询
              let res = await customModelApi.query(view.dataView.model, filter);
              if (res.data.length > 0) {
                this.selected = this.parseData(res.data[0], this.sourceDisplayCode);
                this.selectedData = res.data[0];
              }
            } else if (view.dataView.isDataSource) {
              // 数据源查询
              let res = await dataSourceApi.query(view.dataView.dataSource, filter);
              if (res.table.length > 0) {
                this.selected = this.parseData(res.table[0], this.sourceDisplayCode);
                this.selectedData = res.table[0];
              }
            } else {
              // 普通模型查询
              let res = await modelApi.query(view.dataView.model, filter);
              if (res.data.length > 0) {
                this.selected = this.parseData(res.data[0], this.sourceDisplayCode);
                this.selectedData = res.data[0];
              }
            }
          });
        }
      },
      // 弹出选择框
      dialogSelectOpen() {
        let that = this.$parent;

        while (that.$parent != null) {
          if (that.$refs['dialogTable'] != null) {
            break;
          } else {
            that = that.$parent;
          }
        }

        if (this.multi) {
          this.dialogTable = that.$refs.multiDialogTable;
        } else {
          this.dialogTable = that.$refs.dialogTable;
        }

        this.dialogTable.init(this.source, () => {
          if (!this.readonly && this.source) {
            // if (this.param) {
            //   // 参数完整
            //   this.loadDataEnable = true;
            // } else {
            //   // 参数不完整
            //   this.loadDataEnable = false;
            // }

            //this.$refs.dialogTable.loadData();

            setTimeout(async () => {
              for (let key in this.dialogTable.filterData) {
                delete this.dialogTable.filterData[key];
              }

              if (this.multi) {
                if (this.selectedData != null) {
                  this.dialogTable.setSelected(this.selectedData);
                } else {
                  this.dialogTable.setSelected([]);
                }

                that.openMultiDialogTable(this.param, this.multiSave);
              } else {
                that.openDialogTable(this.param, this.dialogCheck);
              }
            });
          }
        });
      },

      // 弹出选择框移除内容
      dialogSelectRemove() {
        /**
         * 拖动完成事件
         * @property {object} args { index1 来源行序号, index2 目标行序号 }
         */
        this.$emit('update:modelValue', null);
        this.selected = null;
        this.selectedData = null;

        this.$emit('on-change');
      },
      // 弹出选择框选中
      dialogCheck(row) {
        /**
         * 输入事件
         * @property {object} value 选中的值 }
         */
        this.$emit('update:modelValue', this.parseData(row, this.sourceDataCode));

        this.selected = this.parseData(row, this.sourceDisplayCode);
        this.selectedData = row;

        //this.$forceUpdate();

        /**
         * 选中项变化事件
         * @property {object} row 选中行 }
         */
        this.$emit('on-change', row);

        this.dialogTable.close();
      },
      // 多选保存
      multiSave() {
        let selectedData = this.dialogTable.getSelected();
        let data =
          selectedData.length == 0
            ? null
            : selectedData.map(item => {
                return this.parseData(item, this.sourceDataCode);
              });

        let displayData =
          selectedData.length == 0
            ? null
            : selectedData
                .map(item => {
                  return this.parseData(item, this.sourceDisplayCode);
                })
                .join(',');

        /**
         * 输入事件
         * @property {object} value 选中的值 }
         */
        this.$emit('update:modelValue', JSON.stringify(data));
        this.selected = displayData;
        this.selectedData = data;

        //this.$forceUpdate();

        /**
         * 选中项变化事件
         * @property {object} row 选中行 }
         */
        this.$emit('on-change', data, displayData);

        this.dialogTable.close();
      }
    }
  };
</script>
