<template>
  <zj-page-container direction="row">
    <div style="min-width: 240px; max-width: 240px; height: 100%">
      <zj-page-container>
        <div class="title">
          <el-button style="margin-right: 5px" size="mini" icon="el-icon-search" @click="getTreeListData"></el-button>
          <el-input size="mini" v-model="filterText" placeholder="请输入内容"></el-input>
        </div>
        <zj-page-fill>
          <el-tree
            :data="treeList"
            :props="defaultProps"
            default-expand-all
            :highlight-current="true"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
            :filter-node-method="filterNode"
            ref="listTree"
          >
            <span class="custom-tree-node" slot-scope="{ node }">
              <span>{{ node.label }}</span>
            </span>
          </el-tree>
        </zj-page-fill>
      </zj-page-container>
    </div>
    <template-page
      ref="pageRef"
      :getList="getList"
      :columnParsing="columnParsing"
      :optionsEvensGroup="optionsEvensGroup"
      :tableAttributes="tableAttributes"
      :tableEvents="tableEvents"
      :operationColumnWidth="160"
      :operation="operation()"
      :exportList="exportList"
    >
    </template-page>
    <div class="cartographer_big">
      <el-dialog title="配置" width="100%" :modal="false" :visible.sync="formDialog" :before-close="formDialogClose">
        <zj-page-container v-if="formDialog">
          <zj-page-fill class="neibuview">
            <zj-form-container ref="formRef" :form-data="formData" :form-attributes="{ size: 'mini' }">
              <zj-form-module title="配置信息" label-width="90px" :form-data="formData" :form-items="formItems">
              </zj-form-module>
            </zj-form-container>
          </zj-page-fill>
          <div>
            <div style="box-sizing: border-box; padding: 10px">
              <el-button size="mini" @click="formDialogClose">关闭</el-button>
              <el-button size="mini" type="primary" @click="queding">确定</el-button>
            </div>
          </div>
        </zj-page-container>
      </el-dialog>
    </div>
  </zj-page-container>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import {
  dispatchListDispatch,
  dispatchListDispatchExport,
  dispatchDelDispatch,
  dispatchImport,
  dispatchPList,
  dispatchCList,
  dispatchAList,
  dispatchSList,
  dispatchChannel,
  dispatchSmallList,
  dispatchCategoryList,
  dispatchSourceList,
  dispatchSaveDispatch
} from '@/api/streetConfiguration.js'
import operation_mixin from '@/components/template/operation_mixin.js'
import import_mixin from '@/components/template/import_mixin.js'
import { getDepartmentList } from '@/api/setting'
import { commonTemplateDownload } from '@/api/common.js'
import { required, mobileRequired, mobile, httpUrl, email } from '@/components/template/rules_verify.js'
export default {
  components: {
    TemplatePage
  },
  mixins: [operation_mixin, import_mixin],
  data() {
    return {
      // 表格属性
      tableAttributes: {},
      // 表格事件
      tableEvents: {},
      visible: false,
      item: null,
      treeList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      filterText: '',
      dataList: [],
      provinceList: [],
      cityList: [],
      areaList: [],
      streetList: [],
      orderSourceIdsList: [],
      orderSmallIdsList: [],
      orderChannelIdsList: [],
      categoryIdsList: [],
      formData: {
        provinceCode: '',
        provinceName: '',
        cityCode: '',
        cityName: '',
        areaCode: '',
        areaName: '',
        streetCode: '',
        streetName: '',
        categoryIds: [],
        orderChannelIds: [],
        orderSmallIds: [],
        orderSourceIds: [],
        websitId: '',
        websitName: ''
      },
      formDialog: false
    }
  },
  mounted() {
    this.getTreeListData()
  },
  computed: {
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth('add', {
              click: () => {
                this.formDialog = true
              }
            })
          ],
          [
            this.optionsEvensAuth('downloadImportTemplate', {
              click: () => {
                commonTemplateDownload({ name: '自动派工配置.xlsx' }, `自动派工配置`)
                  .then(res => {
                    this.$message({
                      message: '下载成功',
                      type: 'success'
                    })
                  })
                  .catch(err => {
                    this.$message.error('下载失败')
                  })
              }
            })
          ],
          [
            this.optionsEvensAuth('import', ({ moduleName }) => {
              return {
                name: moduleName,
                render: () => {
                  return this.importButton(dispatchImport, moduleName)
                }
              }
            })
          ]
        ]
      ]
    },
    formItems() {
      return [
        {
          name: 'el-select',
          md: 6,
          options: this.dataList,
          attributes: {
            placeholder: '请选择',
            clearable: true,
            filterable: true
          },
          formItemAttributes: {
            label: '选择网点',
            prop: 'websitId',
            rules: [...required]
          },
          events: {
            change: val => {
              if (val) {
                this.formData.websitName = this.dataList.find(item => item.value == val).label
              } else {
                this.formData.websitName = ''
              }
            }
          }
        },
        {
          name: 'el-select',
          md: 6,
          formItemAttributes: {
            label: '选择省份', //省
            prop: 'provinceCode',
            rules: [...required],
            errLabel: '省'
          },
          options: this.provinceList,
          attributes: {
            clearable: true,
            filterable: true,
            placeholder: '请选择',
            loading: !this.provinceList.length
          },
          events: {
            focus: val => {
              dispatchPList(this.getPam('provinceCode')).then(res => {
                this.provinceList = res.data.map(item => ({
                  value: item.keyId,
                  label: item.valueName
                }))
              })
            },
            change: val => {
              // 获取省名称
              this.formData.provinceName = this.provinceList?.find(item => item.value === val)?.label || ''
            }
          }
        },
        {
          name: 'el-select',
          md: 6,
          formItemAttributes: {
            label: '选择城市', //市
            prop: 'cityCode',
            rules: [...required],
            errLabel: '市'
          },
          options: this.cityList,
          attributes: {
            clearable: true,
            filterable: true,
            placeholder: '请选择',
            loading: !this.cityList.length
          },
          events: {
            focus: val => {
              dispatchCList(this.getPam('cityCode')).then(res => {
                this.cityList = res.data.map(item => ({
                  value: item.keyId,
                  label: item.valueName
                }))
              })
            },
            change: val => {
              // 获取市名称
              this.formData.cityName = this.cityList?.find(item => item.value === val)?.label || ''
            }
          }
        },
        {
          name: 'el-select',
          md: 6,
          formItemAttributes: {
            label: '选择区域', //区
            prop: 'areaCode',
            rules: [...required],
            errLabel: '区'
          },
          options: this.areaList,
          attributes: {
            clearable: true,
            filterable: true,
            placeholder: '请选择',
            loading: !this.areaList.length
          },
          events: {
            focus: val => {
              dispatchAList(this.getPam('areaCode')).then(res => {
                this.areaList = res.data.map(item => ({
                  value: item.keyId,
                  label: item.valueName
                }))
              })
            },
            change: val => {
              // 获取区名称
              this.formData.areaName = this.areaList?.find(item => item.value === val)?.label || ''
            }
          }
        },
        {
          name: 'el-select',
          md: 6,
          formItemAttributes: {
            label: '选择街道', //街道
            prop: 'streetCode',
            rules: [...required],
            errLabel: '街道'
          },
          options: this.streetList,
          attributes: {
            clearable: true,
            filterable: true,
            placeholder: '请选择',
            loading: !this.streetList.length
          },
          events: {
            focus: val => {
              dispatchSList(this.getPam('streetCode')).then(res => {
                this.streetList = res.data.map(item => ({
                  value: item.keyId,
                  label: item.valueName
                }))
              })
            },
            change: val => {
              // 获取街道名称
              this.formData.streetName = this.streetList?.find(item => item.value === val)?.label || ''
            }
          }
        },
        {
          name: 'zj-paging-pull-down',
          options: this.orderChannelIdsList,
          md: 24,
          attributes: {
            placeholder: '请选择',
            clearable: true,
            filterable: true,
            multiple: true,
            loading: !this.orderChannelIdsList.length
          },
          formItemAttributes: {
            label: '工单渠道',
            prop: 'orderChannelIds',
            rules: [...required]
          },
          events: {
            focus: val => {
              dispatchChannel(this.getPam('orderChannelIds')).then(res => {
                this.orderChannelIdsList = res.data.map(item => ({
                  value: item.keyId,
                  label: item.valueName
                }))
              })
            }
          }
        },
        {
          name: 'zj-paging-pull-down',
          options: this.orderSmallIdsList,
          md: 24,
          attributes: {
            placeholder: '请选择',
            clearable: true,
            filterable: true,
            multiple: true,
            loading: !this.orderSmallIdsList.length
          },
          formItemAttributes: {
            label: '工单类型',
            prop: 'orderSmallIds',
            rules: [...required]
          },
          events: {
            focus: val => {
              dispatchSmallList(this.getPam('orderSmallIds')).then(res => {
                this.orderSmallIdsList = res.data.map(item => ({
                  value: item.keyId,
                  label: item.valueName
                }))
              })
            }
          }
        },
        {
          name: 'zj-paging-pull-down',
          options: this.categoryIdsList,
          md: 24,
          attributes: {
            placeholder: '请选择',
            clearable: true,
            filterable: true,
            multiple: true,
            loading: !this.categoryIdsList.length
          },
          formItemAttributes: {
            label: '产品大类',
            prop: 'categoryIds',
            rules: [...required]
          },
          events: {
            focus: val => {
              dispatchCategoryList(this.getPam('categoryIds')).then(res => {
                this.categoryIdsList = res.data.map(item => ({
                  value: item.keyId,
                  label: item.valueName
                }))
              })
            }
          }
        },
        {
          name: 'zj-paging-pull-down',
          options: this.orderSourceIdsList,
          md: 24,
          attributes: {
            placeholder: '请选择',
            clearable: true,
            filterable: true,
            multiple: true,
            loading: !this.orderSourceIdsList.length
          },
          formItemAttributes: {
            label: '工单来源',
            prop: 'orderSourceIds',
            rules: [...required]
          },
          events: {
            focus: val => {
              dispatchSourceList(this.getPam('orderSourceIds')).then(res => {
                this.orderSourceIdsList = res.data.map(item => ({
                  value: item.keyId,
                  label: item.valueName
                }))
              })
            }
          }
        }
      ]
    }
  },
  watch: {
    filterText(val) {
      this?.$refs?.listTree?.filter?.(val)
    }
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    // 请求属性数据
    getTreeListData() {
      var list_ = []
      function dg(list, pname = []) {
        for (let { children, name, ...item } of list) {
          list_.push({ ...item, name: name, pname: [...pname] })
          if (children && children.length) dg(children, [...pname, name])
        }
      }
      getDepartmentList().then(res => {
        this.treeList = res.data
        this.$refs.pageRef.refreshList()
        dg(JSON.parse(JSON.stringify(res.data)))
        this.dataList = [...list_]
          .filter(item => {
            return item.type === 'C'
          })
          .map(item => {
            return {
              label: item.name,
              value: item.websitId
            }
          })
      })
    },
    // 树形选中
    handleNodeClick(e) {
      this.$refs.pageRef.refreshList()
    },
    // 列表请求函数
    getList(pam, cb) {
      try {
        cb && cb(pam)
        return dispatchListDispatch(pam)
      } catch (err) {}
    },
    // 列表导出函数
    exportList: dispatchListDispatchExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    operation() {
      return this.operationBtn({
        // edit: {
        //   click: ({ row, index, column }) => {}
        // },
        del: {
          prompt: '请确认是否删除该数据, 是否继续?',
          click: ({ row, index, column }) => {
            dispatchDelDispatch({
              id: row.id
            }).then(res => {
              if (res.code == 200) {
                this.$message({ type: 'success', message: '删除成功!' })
                this.$refs.pageRef.refreshList()
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        }
      })
    },
    getPam(key) {
      var keys = [
        'provinceCode',
        'cityCode',
        'areaCode',
        'streetCode',
        'dictCode',
        'categoryId',
        'orderSmallId',
        'orderSourceId'
      ].filter(k => k !== key)
      var obj = {}
      keys.map(k => {
        if (this.formData[k]) {
          obj[k] = this.formData[k]
        }
      })
      // console.
      return obj
    },
    formDialogClose() {
      // this.provinceList: [],
      // cityList: [],
      // areaList: [],
      // streetList: [],
      this.formData = {
        provinceCode: '',
        provinceName: '',
        cityCode: '',
        cityName: '',
        areaCode: '',
        areaName: '',
        streetCode: '',
        streetName: '',
        categoryId: '',
        categoryName: '',
        dictCode: '',
        dictValue: '',
        orderSmallId: '',
        orderSmallTypeText: '',
        orderSource: '',
        orderSourceId: '',
        websitId: '',
        websitName: ''
      }
      this.formDialog = false
    },
    queding() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          dispatchSaveDispatch(this.formData).then(res => {
            this.$message({ type: 'success', message: `配置成功!` })
            this.$refs.pageRef.refreshList()
            this.formDialogClose()
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.title {
  width: 100%;
  padding: 20px 0 10px 20px;
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  border-bottom: 1px solid #cccccc;
  font-weight: bold;
}
.custom-tree-node {
  display: inline-block;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.neibuview {
  box-sizing: border-box;
  padding-left: 16px;

  ::v-deep & > .zj-page-fill-scroll {
    box-sizing: border-box;
    padding-right: 16px;

    & > div:nth-child(1) {
      margin-top: 20px;
    }
  }
}
</style>
