<template>
  <template-page
    ref="pageRef"
    :getList="getList"
    :operation="operation()"
    :optionsEvensGroup="optionsEvensGroup"
    :exportList="exportList"
    :columnParsing="columnParsing"
    :tableAttributes="tableAttributes"
    :tableEvents="tableEvents"
    :operationColumnWidth="200"
  >
    <!-- 弹窗 -->
    <el-dialog
      title="提货车辆档案"
      :visible.sync="dialogForm"
      width="40%"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <el-form ref="addForm" :rules="rules" :model="addForm" label-width="120px" class="demo-ruleForm">
        <el-form-item label="经销商名称" prop="customerId">
          <el-select v-model="addForm.customerId" placeholder="请选择经销商名称">
            <el-option v-for="item in dealerList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="车牌号" prop="carBrand">
              <el-input v-model="addForm.carBrand"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="mobile">
              <el-input v-model="addForm.mobile"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="车型" prop="carType">
              <el-input v-model="addForm.carType"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="体积" prop="volume">
              <el-input v-model="addForm.volume">
                <i class="el-input__icon" slot="suffix">m³ </i>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelFn">取 消</el-button>
        <el-button type="primary" @click="addDataListFn">确 定</el-button>
      </div>
    </el-dialog>
  </template-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import {
  getCarList,
  addDataListApi,
  delCarFn,
  editDataListApi,
  v2TakerCarRecordList,
  v2TakerCarRecordListExport
} from '@/api/basic_data/taker'
import { getDealerList } from '@/api/basic_data/dealer'
import { downloadFiles } from '@/utils/util'

export default {
  components: {
    TemplatePage
  },
  data() {
    return {
      // 事件组合
      optionsEvensGroup: [
        [
          [
            {
              name: '新增',
              click: () => {
                this.addDataList()
              },
              isRole: this.$checkBtnRole('add', this.$route.meta.roles)
            }
          ]
        ],
        [
          [
            {
              name: '批量删除',
              click: async () => {
                if (this.recordSelected.length === 0) {
                  this.$message.error('请选择需要删除的数据')
                  return
                }
                this.delFn()
              },
              isRole: this.$checkBtnRole('del', this.$route.meta.roles)
            }
          ]
        ]
      ],
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      recordSelected: [],

      listLoading: false, // 列表加载loading
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      addForm: {
        customerId: '',
        mobile: '',
        carType: '',
        volume: '',
        carBrand: ''
      },
      rules: {
        customerId: [{ required: true, message: '请选择活动区域', trigger: 'change' }],
        mobile: [
          {
            required: true,
            message: '请输入联系电话',
            trigger: 'blur'
          },
          {
            pattern: /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/,
            message: '联系电话格式不正确',
            trigger: 'blur'
          }
        ],
        // carType: [{ required: true, message: "车型不能为空", trigger: "blur" }],
        // volume: [{ required: true, message: "体积不能为空", trigger: "blur" }],
        carBrand: [{ required: true, message: '车牌号不能为空', trigger: 'blur' }]
      },
      dialogForm: false,
      isCollapse: true,
      dataList: [],
      searchForm: {
        customerName: '',
        carBrand: ''
      },
      dealerList: [],
      ids: []
    }
  },
  computed: {
    exParams() {
      return {
        carBrand: this.searchForm.carBrand,
        customerName: this.searchForm.customerName
      }
    }
  },
  async created() {
    this.getDataList()
    this.getDealerDataList({ pageNum: 1, pageSize: 10 })
  },
  methods: {
    // 列表请求函数
    getList: v2TakerCarRecordList,
    // 列表导出函数
    exportList: v2TakerCarRecordListExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    operation() {
      return (h, { row, index, column }) => {
        return (
          <div class="operation-btns">
            {this.$checkBtnRole('del', this.$route.meta.roles) ? (
              <el-popconfirm
                onConfirm={async () => {
                  this.delFn(row.id)
                }}
                title="是否确定需要删除该项内容?"
              >
                <el-button slot="reference" size="mini" type="text">
                  删除
                </el-button>
              </el-popconfirm>
            ) : (
              ''
            )}

            {this.$checkBtnRole('edit', this.$route.meta.roles) ? (
              <el-button
                size="mini"
                type="text"
                onClick={async () => {
                  this.editFn(row)
                }}
              >
                编辑
              </el-button>
            ) : (
              ''
            )}
          </div>
        )
      }
    },

    // 筛选部分数据或者单个
    hanleSelect(selection) {
      // this.ids = selection.map((k) => {
      //   return k.id;
      // });
      // console.log(selection);
      this.ids = selection.map(v => v.id)
      // console.log(this.ids);
    },
    // //导出
    // exportFn() {
    //   let screenData = {
    //     customerName: this.searchForm.customerName,
    //     carBrand: this.searchForm.carBrand,
    //   };
    //   downloadFiles("/take-car-record/export", screenData);
    // },
    //取消
    async cancelFn() {
      if (this.addForm.id) {
        this.addForm = {
          customerId: '',
          mobile: '',
          carType: '',
          volume: '',
          carBrand: ''
        }
      } else {
        await this.$refs.addForm.resetFields()
      }
      this.dialogForm = false
    },
    //编辑
    editFn(data) {
      this.addForm = data
      this.dialogForm = true
    },
    //重置
    clearFn() {
      console.log(this.$refs.searchForm)
      this.$refs.searchForm.resetFields()
    },
    //搜索
    async searchFn() {
      this.currentPage = 1
      await this.getDataList()
    },
    //删除
    async delFn(ids) {
      if (ids) {
        let arr = []
        arr.push(ids)
        let res = arr.toString()
        await delCarFn({ ids: res })
      } else {
        let res = this.recordSelected.map(v => v.id).toString()
        await delCarFn({ ids: res })
      }

      this.$message.success('删除成功')
      this.ids = []
      // this.getDataList()
      this.$refs.pageRef.refreshList()
    },
    //获取经销商数据
    async getDealerDataList(data) {
      const res = await getDealerList(data)
      this.dealerList = res.data.records
    },
    //新增
    async addDataList() {
      this.addForm = {
        customerId: '',
        mobile: '',
        carType: '',
        volume: '',
        carBrand: ''
      }

      this.dialogForm = true
    },
    async addDataListFn() {
      await this.$refs.addForm.validate()

      const res = this.dealerList.filter(v => v.id === this.addForm.customerId)[0]

      if (this.addForm.id) {
        await editDataListApi({ ...this.addForm })
        this.$message.success('编辑成功')
      } else {
        await addDataListApi({ ...this.addForm, orgNumber: res.useOrgNumber })
        this.$message.success('添加成功')
      }

      // console.log(res);
      //
      // this.addForm = {
      //   customerId: "",
      //   mobile: "",
      //   carType: "",
      //   volume: "",
      //   carBrand: "",
      // };
      await this.$refs.addForm.resetFields()
      // this.getDataList()
      this.$refs.pageRef.refreshList()
      this.dialogForm = false
    },
    //获取列表数据
    async getDataList() {
      let params = {
        carBrand: this.searchForm.carBrand,
        customerName: this.searchForm.customerName,
        pageSize: this.pageSize,
        pageNum: this.currentPage
      }
      const res = await getCarList(params)
      this.dataList = res.data.records
      this.listTotal = res.data.total
    },

    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getDataList()
    },
    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val
      this.getDataList()
    }
  }
}
</script>

<style lang="scss" scoped>
.add-right {
  margin-right: 10px;
}
// ::v-deep .el-popover__reference {
//   margin-left: 10px;
// }
::v-deep .el-date-editor {
  width: 100%;
}
::v-deep .el-select {
  width: 100%;
}
::v-deep .el-col-9 .el-button {
  padding: 5px;
}
::v-deep .el-dialog__header {
  background-color: #dddddd;
}
</style>
