<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.car_delete"
                   @click="handleDelete">删 除
        </el-button>
        <cy-excel-import :flag="6" file-name="车辆信息导入模板" @success="onLoad(page)"></cy-excel-import>
      </template>
      <!--      <template slot="personId" slot-scope="scope">-->
      <!--&lt;!&ndash;        <el-tag type="primary" @click="personClick(scope.row)">{{scope.row.$personId}}</el-tag>&ndash;&gt;-->
      <!--        <el-tag type="primary">{{scope.row.$personId}}</el-tag>-->
      <!--      </template>-->
    </avue-crud>
    <el-dialog title="人员画像" :visible.sync="dialogOpen" :fullscreen="true" :modal-append-to-body="false" center>
      <cy-person-file :personId="personId"></cy-person-file>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/estate/car";
  // import CyPersonFile from "../../components/file/cy-person-file";
  import {mapGetters} from "vuex";
  import {validateLicense, validatePhone} from "../../util/validator";
  import {getList as getAgencyList} from "@/api/community/agency";
  import {getList as getResidentialList} from "@/api/community/residential";
  // import CyExcelImport from "../../components/excel/cy-excel-import";

  export default {
    // components: {
    //   CyExcelImport,
    //   CyPersonFile
    // },
    data() {
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        dialogOpen: false,
        personId: '',
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "车牌号",
              prop: "number",
              width: 200,
              rules: [{
                required: true,
                message: "请输入车牌号",
              },{
                validator: validateLicense,
                trigger: "blur"
              }]
            }, {
              label: "车辆类型",
              prop: "type",
              type: "select",
              width: 150,
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=car-type",
              props: {
                label: "dictValue",
                value: "dictKey",
              },
              dataType: "number",
              rules: [{
                required: true,
                message: "请输入车辆类型",
                trigger: "blur"
              }]
            },
            {
              label: "所属社区",
              prop: "agencyName",
              editDisplay: false,
              addDisplay: false,
            },
            {
              label: "所属社区",
              prop: "agencyId",
              search: true,
              searchFilterable: true,
              filterable: true,
              cascaderItem: ['residentialId'],
              type: "select",
              // remote: true,
              dicUrl: "/api/cyzh-community/agency/list?size=9999",
              dicFormatter:(res)=>{
                return res.data.records;//返回字典的层级结构
              },
              props: {
                label: "name",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请选择所属社区",
                trigger: "blur"
              }],
              hide: true,
              viewDisplay: false,
            },
            {
              label: "所属小区",
              prop: "residentialName",
              editDisplay: false,
              addDisplay: false
            },
            {
              label: "所属小区",
              prop: "residentialId",
              type: "select",
              search: true,
              // dataType:'string',
              cascaderItem: ["parkingLotId"],
              dicUrl: "/api/cyzh-community/residential/list?agencyId={{key}}",
              dicFormatter:(res)=>{
                return res.data.records;//返回字典的层级结构
              },
              // dicFlag: false,
              filterable: true,
              props: {
                label: "name",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请选择所属小区",
                trigger: "blur"
              }],
              hide: true,
              viewDisplay: false,
            },
            {
              label: "所属车场",
              prop: "parkingLotId",
              type: "select",
              search: true,
              // overHidden: true,
              // remote: true,
              dicUrl: "/api/cyzh-estate/parkinglot/list?size=500&residentialId={{key}}",
              props: {
                label: 'parkName',
                value: 'id'
              },
              dicFormatter: (res) => {
                return res.data.records;
              },

              rules: [{
                require: true,
                message: "请选择所属车场",
                trigger: "blur"
              }]
            },
            {
              label: "车主姓名",
              prop: "personName",
              search: true,
              width: 150,
              searchSpan: 4,
              rules: [{
                required: true,
                message: "请输入车主姓名",
                trigger: "blur"
              }]
            },
            {
              label: "车主电话",
              prop: "personPhone",
              search: true,
              width: 200,
              searchSpan: 4,
              rules: [{
                required: true,
                message: "请输入车主电话",
              },{
                validator: validatePhone,
                trigger: "blur"
              }]
            },
            {
              label: "车辆性质",
              prop: "properties",
              hide:true,
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=car_properties",
              props: {
                label: "dictValue",
                value: "dictKey",
              },
              dataType: "number",
              rules: [{
                required: false,
                message: "请选择车辆性质",
                trigger: "blur"
              }]
            },
            {
              label: "车辆型号",
              prop: "model",
              hide: true,
              rules: [{
                required: false,
                message: "请输入车辆型号",
                trigger: "blur"
              }]
            },
            // {
            //   label: "燃油类别",
            //   prop: "fuelCategory",
            //   hide: true,
            //   type: "select",
            //   dicUrl: "/api/blade-system/dict-biz/dictionary?code=fuel-category",
            //   props: {
            //     label: "dictValue",
            //     value: "dictKey",
            //   },
            //   rules: [{
            //     required: false,
            //     message: "请输入燃油类别",
            //     trigger: "blur"
            //   }]
            // },
            {
              label: "车身颜色",
              prop: "color",
              hide: true,
              rules: [{
                required: false,
                message: "请输入车身颜色",
                trigger: "blur"
              }]
            },{
              label: "占用车位",
              prop: "parkinglot",
              type: "select",
              hide: true,
              dicData:[
                {
                  label:'占用',
                  value: 1
                },{
                  label:'空闲',
                  value: 0
                }
              ],
              rules: [{
                required: false,
                message: "请选择是否占用车位",
                trigger: "blur"
              }]
            },{
              label: "车辆照片",
              prop: "carImg",
              listType: 'picture-img',
              type: "upload",
              hide: true,
              propsHttp: {
                res: "data",
                url: "link"
              },
              //加水印
              // canvasOption: {
              //   text: 'bladex',
              //   ratio: 0.1
              // },
              action: "/api/blade-resource/oss/endpoint/put-file",
              tip: "只能上传jpg/png图片，且不超过500kb"
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.car_add, false),
          viewBtn: this.vaildData(this.permission.car_view, false),
          delBtn: this.vaildData(this.permission.car_delete, false),
          editBtn: this.vaildData(this.permission.car_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    watch: {
      "form.agencyId"() {
        getAgencyList(1, 10, {id: this.form.agencyId}).then(res => {
          this.form.agencyName = res.data.data.records[0].name;
        })
      },
      "form.residentialId"() {
        getResidentialList(1, 10, {id: this.form.residentialId}).then(res => {
          this.form.residentialName = res.data.data.records[0].name;
          console.log(JSON.stringify(this.form))
        })
      },
      "form.parkingLotId"() {
          console.log(JSON.stringify(this.form))
      }
    },
    mounted() {
      let tenantType = localStorage.getItem("tenantType");
      const agencyColumn = this.findObject(this.option.column, "agencyId");
      const residentialColumn = this.findObject(this.option.column, "residentialId");
      if (tenantType == 1) { //园区
        agencyColumn.label = "所属园区";
        residentialColumn.label = "所属区域";
      } else { //社区
        agencyColumn.label = "所属社区";
        residentialColumn.label = "所属小区";
      }
    },
    methods: {
      personClick(row) {
        this.personId = row.personId;
        // this.dialogOpen = true;
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
