<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()"
    >
      <Button slot="prepend" :size="size" custom-icon="fa fa-search" @click="dialogSelectOpen()"></Button>
    </Input>
    <modal-table ref="dialogTable" :view-code="source" :selectEnable="multi" :footerEnable="multi" v-if="dialogActive">
      <template slot-scope="{ row }" slot="command">
        <Button size="small" v-if="!multi" type="primary" custom-icon="fa fa-check" @click="dialogCheck(row)">{{ $t('Front_Btn_Select') }}</Button>
      </template>
      <template slot="footer">
        <Button type="primary" custom-icon="fa fa-save" @click="multiSave">{{ $t('Front_Btn_OK') }}</Button>
        <Button type="default" custom-icon="fa fa-times" @click="close()">{{ $t('Front_Btn_Close') }}</Button>
      </template>
    </modal-table>
  </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,
        dialogActive: false
      };
    },
    props: {
      /**
       * @model
       */
      value: {
        type: String
      },
      /**
       * 数据源
       */
      source: {
        type: String
      },
      /**
       * 大小
       * @values small, default, large
       */
      size: {
        type: String
      },
      /**
       * 数据源数据列名
       */
      sourceDataCode: {
        type: String
      },
      /**
       * 数据源显示列名
       */
      sourceDisplayCode: {
        type: String
      },
      /**
       * 参数
       */
      param: {
        type: Object
      },
      /**
       * 只读
       */
      readonly: {
        type: Boolean,
        default: false
      },
      /**
       * 控件宽度
       */
      controlWidth: {
        type: Number
      },
      /**
       * 能否多选
       */
      multi: {
        type: Boolean,
        default: false
      }
    },
    computed: {},
    watch: {
      value() {
        this.showSelected();

        //this.changed = false;
      }
    },
    mounted() {
      this.showSelected();
    },
    methods: {
      ...mapActions('admin/dataView', { loadDataView: 'load' }),
      // 显示选择项
      showSelected() {
        if (this.value == null) {
          this.selected = null;
          this.selectedData = null;
          return;
        } else if (this.multi) {
          let filter = {
            page: 1,
            per: 999
          };
          filter[this.sourceDataCode] = JSON.parse(this.value).join(',');

          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 = res.data
                  .map(item => {
                    return this.parseData(item, this.sourceDisplayCode);
                  })
                  .join(',');
                this.selectedData = res.data;

                this.$forceUpdate();
              }
            } 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;

                this.$forceUpdate();
              }
            } else {
              let res = await modelApi.query(view.dataView.model, filter);
              if (res.data.length > 0) {
                this.selected = res.data
                  .map(item => {
                    return this.parseData(item, this.sourceDisplayCode);
                  })
                  .join(',');
                this.selectedData = res.data;

                this.$forceUpdate();
              }
            }
          });
        } else {
          let filter = {
            page: 1,
            per: 1
          };
          filter[this.sourceDataCode] = this.value;

          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];

                this.$forceUpdate();
              }
            } 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];

                this.$forceUpdate();
              }
            } 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];

                this.$forceUpdate();
              }
            }
          });
        }
      },
      // 弹出选择框
      dialogSelectOpen() {
        if (!this.readonly && this.source) {
          this.dialogActive = true;

          setTimeout(async () => {
            if (this.multi) {
              if (this.selectedData != null) {
                this.$refs.dialogTable.setSelected(this.selectedData);
              } else {
                this.$refs.dialogTable.setSelected([]);
              }
            }

            this.$refs.dialogTable.open(this.param);
          });
        }
      },
      // 弹出选择框选中
      dialogCheck(row) {
        /**
         * 输入事件
         * @property {object} value 选中的值 }
         */
        this.$emit('input', 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.$refs.dialogTable.close();
      },
      // 弹出选择框移除内容
      dialogSelectRemove() {
        /**
         * 拖动完成事件
         * @property {object} args { index1 来源行序号, index2 目标行序号 }
         */
        this.$emit('input', null);
        this.selected = null;
        this.selectedData = null;

        this.$emit('on-change');
      },
      // 多选保存
      multiSave() {
        let selectedData = this.$refs.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('input', JSON.stringify(data));
        this.selected = displayData;
        this.selectedData = data;

        this.$forceUpdate();

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

        this.$refs.dialogTable.close();
      },
      // 关闭
      close() {
        this.$refs.dialogTable.close();
      }
    }
  };
</script>
