<template>
  <div>
    <el-dialog
      append-to-body
      width="70%"
      :title="title"
      :visible.sync="visible"
      @open="handleOpenDialog"
    >
      <div v-if="subtitle" style="margin-bottom: 10px; margin-top: -15px" v-text="subtitle"></div>
      <avue-crud
        ref="supplierCrud"
        :data="crudList"
        :option.sync="supplierSelectDialog.option"
        :page.sync="supplierSelectDialog.page"
        @current-change="currentChange"
        @refresh-change="refreshChange"
        @row-click="currentRowChange"
        @search-change="searchChange"
        @size-change="sizeChange"
      >
        <!-- <template slot-scope="scope" slot="accessCategorySearch">
          <el-cascader
            class="el-autocomplete"
            clearable
            filterable
            size="small"
            v-model="scope.row.accessCategory"
            :options="casOptions"
            :props="props"
          ></el-cascader>
        </template> -->
        <template slot-scope="scope" slot="checked">
          <el-checkbox
            v-model="scope.row.itemStatus"
            @change="(value) => handleCheckChange(value, scope.row)"
          >
          </el-checkbox>
        </template>
        <template slot="menuLeft">
          <el-button type="primary" size="small" plain @click.stop="doAction()">
            {{ btnText }}
          </el-button>
        </template>
      </avue-crud>
    </el-dialog>
  </div>
</template>
<script>
import supplierSelectDialog from './const/supplierSelectBoxDialog';
import commonApi from '../../../lib/api/index';
import { MaterialService } from '../../../lib/api/materials';
import { ft } from '../../../lib/utils';

const LABELS = {
  data: ft('i18n_common_data', '数据'),
  failedToQueryData: ft('i18n_common_failed_to_query_specified_data', '查询?数据失败'),
  pleaseSelect: ft('i18n_common_please_select', '请选择'),
  ok: ft('i18n_common_ok', '确定'),
  selectAll: ft('i18n_common_select_all', '全选'),
  supplier: ft('i18n_common_supplier', '供应商')
};

export default {
  name: 'SelectSupplierBoxDialog',
  props: {
    btnText: { type: String, default: LABELS.ok }, // 保存按钮文字
    title: { type: String, default: '' }, // dialog 标题
    subtitle: { type: String, default: '' }, // dialog 副标题
    dialogVisible: { type: Boolean, default: false }, // dialog显隐
    crudObj: Object,
    // 是否多选
    multiple: {
      type: Boolean,
      default: false
    },

    api: {
      type: Function,
      default: commonApi.supplierServer
    },

    listParams: {
      type: Object,
      default: () => {
        return {};
      }
    },

    searchShow: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      visible: this.dialogVisible,
      selectionData: [],
      crudData: [],
      supplierSelectDialog: supplierSelectDialog,
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      queryParam: {},
      crudMultiple: false,
      currentRow: null,
      props: {
        checkStrictly: true,
        label: 'cateName',
        value: 'cateCode'
      },
      casOptions: []
    };
  },
  created() {
    this.crudMultiple = this.multiple;
    this.supplierSelectDialog.option.searchShow = this.searchShow;
    this.getCateData();
  },
  computed: {
    crudList() {
      return this.supplierSelectDialog.data.map((item) => {
        item.itemStatus = this.selectionData
          ? this.selectionData.map((i) => i.toElsAccount).includes(item.toElsAccount)
          : false;
        return item;
      });
    },
    allSelected() {
      let result = true;
      const list = this.selectionData.map((item) => item.toElsAccount);
      this.crudList.forEach((item) => {
        if (!list.includes(item.toElsAccount)) {
          result = false;
        }
      });
      return result;
    }
  },
  watch: {
    visible: function (newValue) {
      this.$emit('update:dialogVisible', newValue);
    },
    dialogVisible: function (newValue) {
      this.visible = newValue;
      const column = this.supplierSelectDialog.option.column[0];
      this.supplierSelectDialog.option.column[0] = {
        ...column,
        renderHeader: (h, { column, $index }) => {
          return h('div', [
            h('el-checkbox', {
              on: { change: this.allSelect },
              props: { value: this.allSelected }
            }),
            h('span', LABELS.selectAll)
          ]);
        }
      };
    }
  },
  methods: {
    allSelect(value) {
      if (value) {
        this.crudList.forEach((row) => {
          const toElsAccount = row.toElsAccount;
          if (
            this.selectionData &&
            this.selectionData.map((item) => item.toElsAccount).includes(toElsAccount)
          ) {
          } else {
            this.selectionData.push({
              supplierName: row.supplierName,
              supplierType: row.firstType,
              supplierLevel: row.supplierLevel,
              toElsAccount: row.toElsAccount
            });
          }
        });
      } else {
        this.crudList.forEach((row) => {
          const toElsAccount = row.toElsAccount;
          if (
            this.selectionData &&
            this.selectionData.map((item) => item.toElsAccount).includes(toElsAccount)
          ) {
            const index = this.selectionData.findIndex(
              (item) => item.toElsAccount === toElsAccount
            );
            this.selectionData.splice(index, 1);
          }
        });
      }
    },

    currentChange(page) {
      this.page.currentPage = page;
      this.getSupplierData(this.queryParam, this.page);
    },

    doAction() {
      const selectItems = this.selectionData;

      if (selectItems.length < 1) {
        this.$message.warning(`${LABELS.pleaseSelect}${LABELS.data}`);
        return;
      }

      this.selectionData = [];
      this.$emit('ok', selectItems);
      this.visible = false;
    },

    getCateData() {
      MaterialService.findMaterialCate().then((res) => {
        if (res.data.code === '200') {
          const resData = res.data.data || [];
          this.casOptions = this.treeMap(resData);
        }
      });
    },

    // 供应商列表 supplierMasterListAction
    getSupplierData(queryCondition = {}, pagination) {
      const params = {
        pageSize: pagination.pageSize,
        currentPage: pagination.currentPage
      };

      const keys = Object.keys(queryCondition);

      for (const key of keys) {
        if (queryCondition[key]) {
          params[key] = queryCondition[key];
        }
      }

      params.toElsAccountName = params.supplierName || '';

      // 外部传递参数
      const listKeys = Object.keys(this.listParams);

      if (listKeys.length > 0) {
        Object.assign(params, this.listParams);
      }

      this.api(params)
        .then((res) => {
          if (res.data && res.data.code === '200' && res.data.data) {
            const data = res.data.data;
            const rows = data.rows;

            this.supplierSelectDialog.data = rows.map((item) => {
              return {
                toElsAccount: item.toElsAccount,
                supplierName: item.toElsAccountName, // supplierName
                firstType: item.firstType,
                supplierLevel: item.supplierLevel,
                accessCategory: item.accessCategory
              };
            });

            this.supplierSelectDialog.page.total = data.total;
            this.supplierSelectDialog.page.pageSize = pagination.pageSize;
            this.supplierSelectDialog.page.currentPage = pagination.currentPage;
            this.suppliersDialogQueryParam = queryCondition;
            this.suppliersDialogPageParam = pagination;
          } else {
            console.log('Failed to list suppliers.', res.data || res);
            this.$message.error(
              res.data.message ||
                LABELS.failedToQueryData.replace('?', LABELS.supplier.toLowerCase())
            );
          }
        })
        .catch((err) => {
          console.log('Error to list suppliers.', err);
          this.$message.error(LABELS.failedToQueryData.replace('?', LABELS.supplier.toLowerCase()));
        });
    },

    handleCheckChange(value, row) {
      const toElsAccount = row.toElsAccount;
      if (
        this.selectionData &&
        this.selectionData.map((item) => item.toElsAccount).includes(toElsAccount)
      ) {
        const index = this.selectionData.findIndex((item) => item.toElsAccount === toElsAccount);
        this.selectionData.splice(index, 1);
      } else {
        this.selectionData.push({
          supplierName: row.supplierName,
          supplierType: row.firstType,
          supplierLevel: row.supplierLevel,
          toElsAccount: row.toElsAccount
        });
      }
    },

    handleOpenDialog() {
      this.page = {
        ...this.page,
        currentPage: 1,
        pageSize: 10
      };
      if (this.visible) {
        this.getSupplierData(this.queryParam, this.page);
        this.selectionData = this.crudObj.selectedSupplier || [];
      }
    },

    refreshChange() {
      this.page.currentPage = 1;
      this.getSupplierData(this.queryParam, this.page);
    },

    searchChange(params, done) {
      this.queryParam = params;
      this.page.currentPage = 1;
      this.getSupplierData(this.queryParam, this.page);
      done();
    },

    sizeChange(pageSize) {
      this.page.currentPage = 1;
      this.page.pageSize = pageSize;
      this.getSupplierData(this.queryParam, this.page);
    },

    toggleSelection(rows) {
      if (!this.$refs.supplierCrud) {
        return;
      }
      if (rows) {
        rows.forEach((row) => {
          this.$refs.supplierCrud.toggleRowSelection(row);
        });
      } else {
        this.$refs.supplierCrud.clearSelection();
      }
    },

    treeMap(resData) {
      for (var i in resData) {
        // resData[i].cateName = resData[i].cateCode + '_' + resData[i].cateName;
        if (resData[i].children) {
          this.treeMap(resData[i].children);
        }
      }
      return resData;
    }
  }
};
</script>

<style>
.el-autocomplete {
  width: 100%;
}
</style>
