<script>

import {
  generateCustomerNo,
  removeCustomer,
  saveCustomer,
  selectCustomerList, selectCustomerPage,
  updateCustomer
} from '../../../api/customer/info'
import dayjs from 'dayjs'
import {getTableDefaultListLanguage, getTableUserListLanguage} from '../../../api/table'
let customer = {
  customerNo: '',
  customerName: '',
  active: '',
}
export default {
  name: 'CustomerInfo',
  props:{
    ofComponents:{
      type:Boolean,
      default:false
    },
    height:{
      type:Number,
      default:730
    }
  },
  data(){
    return{
      no:1,
      size:50,
      total:0,
      customer:{
        ...customer
      },
      saveCustomer:{
        ...customer,
        active: 'Y'
      },
      tableLoading:false,
      saveCustomerVisible:false,
      customerList:[],
      saveCustomerRules:{
        customerName: [
          { required: true, message: 'Please input Customer Name', trigger: ['blur','change'] }
        ],
      },
      columnList:[
        {
          userId: this.$store.state.user.name,
          functionId: 20002,
          serialNumber: '20002TableCustomerNo',
          tableId: "20002Table",
          tableName: "客户信息表",
          columnProp: "customerNo",
          headerAlign: "center",
          align: "left",
          columnLabel: "Customer No",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 80
        },{
          userId: this.$store.state.user.name,
          functionId: 20002,
          serialNumber: '20002TableCustomerName',
          tableId: "20002Table",
          tableName: "客户信息表",
          columnProp: "customerName",
          headerAlign: "center",
          align: "left",
          columnLabel: "Customer Name",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 120
        },{
          userId: this.$store.state.user.name,
          functionId: 20002,
          serialNumber: '20002TableActive',
          tableId: "20002Table",
          tableName: "客户信息表",
          columnProp: "active",
          headerAlign: "center",
          align: "left",
          columnLabel: "Active",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 80
        },{
          userId: this.$store.state.user.name,
          functionId: 20002,
          serialNumber: '20002TableCreateTime',
          tableId: "20002Table",
          tableName: "客户信息表",
          columnProp: "createTime",
          headerAlign: "center",
          align: "left",
          columnLabel: "Created Time",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 80
        },{
          userId: this.$store.state.user.name,
          functionId: 20002,
          serialNumber: '20002TableCreateBy',
          tableId: "20002Table",
          tableName: "客户信息表",
          columnProp: "createBy",
          headerAlign: "center",
          align: "left",
          columnLabel: "Created By",
          columnHidden: false,
          columnImage: false,
          columnSortable: false,
          sortLv: 10,
          status: true,
          fixed: '',
          columnWidth: 80
        },
      ],
    }
  },
  watch:{
    "customer.customerNo"(newVal,oldVal){
      this.customer.customerNo = newVal.toUpperCase()
    }
  },
  methods:{
    handleSave(){
      if (this.saveCustomerVisible){
        this.$refs.saveForm.validate((valid,obj) => {
          if (valid){
            let params = {
              ...this.saveCustomer,
              site:this.$store.state.user.site,
              createBy:this.$store.state.user.name,
              createTime:dayjs().format('YYYY-MM-DD HH:mm:ss')
            }
            saveCustomer(params).then(({data})=>{
              if (data && data.code === 0){
                this.handleSearch();
                this.saveCustomerVisible = false;
                this.$message.success(data.msg)
              }else {
                this.$message.warning(data.msg)
              }
            }).catch((error)=>{
              this.$message.error(error)
            })
          }else {
            Object.keys(obj).forEach(key => {
              this.$message.warning(obj[key][0].message)
              return
            })
          }
        })
      }else {
        let params = {
          site:this.$store.state.user.site,
        }
        generateCustomerNo(params).then(({data})=>{
          if (data && data.code === 0){
            this.saveCustomer.customerNo = data.id;
            this.saveCustomerVisible = true;
          }else {
            this.$message.warning(data.msg)
          }
        }).catch((error)=>{
          this.$message.error(error)
        })
      }

    },
    handleSearch(){
      let params = {
        ...this.customer,
        site:this.$store.state.user.site
      }
      this.tableLoading = true;
      selectCustomerList(params).then(({data})=>{
        if (data && data.code === 0){
          this.customerList = data.rows;
        }else {
          this.$message.warning(data.msg)
        }
        this.tableLoading = false;
      }).catch((error)=>{
        this.tableLoading = false;
        this.$message.error(error)
      })
    },
    handleRowClick(row, column, event, index){
      if (this.ofComponents){
        this.$emit('rowClick', row)
      }else {
        if (index === 0){
          // 处理 点击修改
          this.saveCustomer = {
            ...row,
          }
          this.saveCustomerVisible = true;
        }
      }
    },
    removeCustomer(row){
      removeCustomer(row).then(({data})=>{
        if (data && data.code === 0){
          this.handleSearch();
          this.$message.success(data.msg)
        }else {
          this.$message.warning(data.msg)
        }
      }).catch((error)=>{
        this.$message.error(error)
      })
    },
    closeSaveForm(){
      this.saveCustomer = {
        ...customer,
        active: 'Y'
      }
      this.$refs.saveForm.resetFields();
    },
    handleEdit(){
      this.$refs.saveForm.validate((valid,obj) => {
        if (valid){
          updateCustomer(this.saveCustomer).then(({data})=>{
            if (data && data.code === 0){
              this.handleSearch();
              this.saveCustomerVisible = false;
              this.$message.success(data.msg)
            }else {
              this.$message.warning(data.msg)
            }
          }).catch((error)=>{
            this.$message.error(error)
          })
        }else {
          for (let i = 0; i < Object.keys(obj).length; i++) {
            this.$message.warning(obj[Object.keys(obj)[i]][0].message)
            break
          }
        }
      })
    },
    // 动态列开始 获取 用户保存的 格式列
    async getTableUserColumn (tableId, columnId) {
      let queryTableUser = {
        userId: this.$store.state.user.name,
        functionId: this.$route.meta.menuId,
        tableId: tableId,
        status: true,
        languageCode: this.$i18n.locale
      }
      await getTableUserListLanguage(queryTableUser).then(({data}) => {
        if (data.rows.length > 0) {
          //this.columnList1 = []
          switch (columnId) {
            case 1:
              this.columnList = data.rows
              break;
          }
        } else {
          this.getColumnList(tableId, columnId)
        }
      })
    },

// 获取 tableDefault 列
    async getColumnList (tableId, columnId) {
      let queryTable = {
        functionId: this.$route.meta.menuId,
        tableId: tableId,
        languageCode: this.$i18n.locale
      }
      await getTableDefaultListLanguage(queryTable).then(({data}) => {
        if (!data.rows.length === 0) {
          switch (columnId) {
            case 1:
              this.columnList = data.rows
              break;
          }
        } else {

        }
      })
    },
    handleSelectCustomerPage(){
      let params = {
        ...this.customer,
        site:this.$store.state.user.site,
        no:this.no,
        size:this.size
      }
      this.tableLoading = true;
      selectCustomerPage(params).then(({data})=>{
        if (data && data.code === 0){
          this.customerList = data.rows;
          this.total = data.total;
        }else {
          this.$message.warning(data.msg)
        }
        this.tableLoading = false;
      }).catch((error)=>{
        this.$message.error(error)
        this.tableLoading = false;
      })
    },
    handleSizeChange(val){
      this.size = val;
      this.handleSelectCustomerPage();
    },
    handleCurrentChange(val){
      this.no = val;
      this.handleSelectCustomerPage();
    }
  },
  created () {
    this.handleSelectCustomerPage();
    // this.handleSearch();
    this.getTableUserColumn("20002Table", 1)
  }
}
</script>

<template>
<div>
  <el-form label-position="top" :inline="true" :model="customer" >
    <el-form-item label="Customer No">
      <el-input v-model="customer.customerNo"></el-input>
    </el-form-item>
    <el-form-item label="Customer Name">
      <el-input v-model="customer.customerName"></el-input>
    </el-form-item>
    <el-form-item label="Active">
      <el-select v-model="customer.active" placeholder="">
        <el-option label="All" value=""></el-option>
        <el-option label="Active" value="Y"></el-option>
        <el-option label="Not Active" value="N"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label=" ">
      <el-button type="primary" v-if="!ofComponents" @click="handleSave">New</el-button>
<!--      <el-button type="primary" @click="handleSearch">Query</el-button>-->
      <el-button type="primary" @click="handleSelectCustomerPage">Query</el-button>
    </el-form-item>
  </el-form>
  <el-table
    :height="height"
    :data="customerList" v-loading="tableLoading"
    border @row-dblclick="handleRowClick"
    style="width: 100%;margin-top: 5px">
    <el-table-column v-if="!ofComponents"
                     header-align="center"
                     align="center"
                     width="100"
                     fixed="left"
                     label="Actions">
      <template slot-scope="scope">
        <el-link style="cursor:pointer;" @click="handleRowClick(scope.row, scope.column, $event,0)">Edit</el-link>
        <el-link style="cursor:pointer;" @click="removeCustomer(scope.row)">Delete</el-link>
      </template>
    </el-table-column>
    <el-table-column
      v-for="(item,index) in columnList" :key="index"
      :sortable="item.columnSortable"
      :prop="item.columnProp"
      :header-align="item.headerAlign"
      :show-overflow-tooltip="item.showOverflowTooltip"
      :align="item.align"
      :fixed="item.fixed==''?false:item.fixed"
      :min-width="item.columnWidth"
      :label="item.columnLabel">
      <template slot-scope="scope">
        <span v-if="!item.columnHidden"> {{ scope.row[item.columnProp] }}</span>
        <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]"
                                           style="width: 100px; height: 80px"/></span>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page.sync="no"
    :page-sizes="[50,100, 200, 300, 400]"
    :page-size="size"
    layout="sizes, prev, pager, next,total"
    :total="total">
  </el-pagination>
  <el-dialog v-drag modal-append-to-body :close-on-click-modal="false" :title="`Customer`" @close="closeSaveForm" width="500px" :visible.sync="saveCustomerVisible">
    <el-form label-position="top" :model="saveCustomer" :rules="saveCustomerRules" ref="saveForm">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="Customer No">
            <el-input readonly disabled v-model="saveCustomer.customerNo"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" >
          <el-form-item label=" ">
            <el-checkbox v-model="saveCustomer.active" true-label="Y" false-label="N">Active</el-checkbox>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="Customer Name" prop="customerName" :show-message="false">
            <el-input v-model="saveCustomer.customerName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" v-if="saveCustomer.site" @click="handleEdit">Save</el-button>
      <el-button type="primary" v-else @click="handleSave">Save</el-button>
      <el-button @click="saveCustomerVisible = false">Cancel</el-button>
    </div>
  </el-dialog>
</div>
</template>

<style scoped>

</style>
