<template>
  <template-page
    ref="pageRef"
    :getList="getList"
    :exportList="exportList"
    :columnParsing="columnParsing"
    :optionsEvensGroup="optionsEvensGroup"
    :tableAttributes="tableAttributes"
    :tableEvents="tableEvents"
    :operation="operation()"
  >
    <div class="cartographer_big">
      <el-dialog title="配置" width="100%" :modal="false" :visible.sync="formBool" :before-close="handleClose">
        <zj-page-container v-if="formBool">
          <zj-page-fill class="neibuview">
            <zj-form-container
              ref="formRef"
              :form-data="formData"
              :form-rules="formRules"
              :form-attributes="{ size: 'mini' }"
            >
              <zj-form-module title="一级网点信息" :form-data="formData" :form-items="items" />
              <zj-form-module title="二级网点信息" :form-data="formData" :form-items="items2" />
            </zj-form-container>
          </zj-page-fill>
          <!-- 操作按钮 -->
          <div style="box-sizing: border-box; padding: 10px; text-align: right">
            <el-button size="mini" @click="handleClose">取 消</el-button>
            <el-button v-if="~[0, 1].indexOf(formType)" size="mini" @click="formConfirm" type="primary"
              >确 定</el-button
            >
          </div>
        </zj-page-container>
      </el-dialog>
    </div>
  </template-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import pagingTransfer from '@/components/paging-transfer.vue'
import {
  settleRelaConfigList,
  settleRelaConfigListExport,
  settleRelaConfigAdd,
  settleRelaConfigEdit,
  settleRelaConfigDetail,
  settleRelaConfigQuerySubWebsit,
  settleRelaConfigImport
} from '@/api/settlementRelationshipAllocation'
import { commonTemplateDownload } from '@/api/common.js'
import operation_mixin from '@/components/template/operation_mixin.js'
import { required, requiredValueMin } from '@/components/template/rules_verify.js'
import { getWebsit } from '@/api/customerManagement.js'
import { EventBus } from '@/utils/eventBus'
export default {
  components: { TemplatePage },
  mixins: [import_mixin, operation_mixin],
  data() {
    return {
      // 表格属性
      tableAttributes: {
        selectColumn: false
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      recordSelected: [],
      formBool: false,
      formType: 0,
      formData: {
        companyWechatId: '',
        companyWechatName: '',
        createBy: '',
        createTime: '',
        items: [],
        updateBy: '',
        updateTime: '',
        websitId: ''
      },
      formRules: {},
      websitList: [],
      formInline: {
        websitId: '',
        websitName: ''
      },
      itemsList: []
    }
  },
  computed: {
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth('add', {
              click: () => {
                this.openWindow(() => {
                  this.formType = 0
                  this.formBool = true
                })
              }
            })
          ],
          [
            this.optionsEvensAuth('downloadImportTemplate', {
              click: () => {
                commonTemplateDownload({ name: '结算上下级关系配置模板.xlsx' }, `${this.$route.meta.title}`)
                  .then(res => {
                    this.$message({
                      message: '下载成功',
                      type: 'success'
                    })
                  })
                  .catch(err => {
                    this.$message.error('下载失败')
                  })
              }
            })
          ],
          [
            this.optionsEvensAuth('import', ({ moduleName }) => {
              return {
                name: moduleName,
                render: () => {
                  return this.importButton(settleRelaConfigImport, moduleName)
                }
              }
            })
          ]
        ]
      ]
    },

    items() {
      return [
        {
          name: 'el-select',
          md: 12,
          options: this.websitList.map(item => ({ label: `(${item.websitId})${item.name}`, value: item.websitId })),
          attributes: {
            clearable: true,
            filterable: true,
            disabled: false,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '一级网点',
            prop: 'websitId',
            rules: [...required]
          },
          events: {
            change: val => {
              var data = this.websitList.find(item => item.websitId === val)
              this.formData.websitName = data?.name || ''
            }
          }
        },
        {
          name: 'slot-component',
          md: 12,
          attributes: {},
          formItemAttributes: {
            label: '',
            prop: '',
            rules: []
          },
          render: (h, { props, onInput }) => {
            return null
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '创建人',
            prop: 'createBy'
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '创建时间',
            prop: 'createTime'
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '修改人',
            prop: 'updateBy'
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '修改时间',
            prop: 'updateTime'
          }
        }
      ]
    },
    items2() {
      return [
        {
          name: 'slot-component',
          md: 24,
          attributes: {},
          formItemAttributes: { label: '', 'label-width': '0px', prop: 'items', rules: [] },
          render: (h, { props, onInput }) => {
            var { formData } = props
            return (
              <div>
                <div>
                  <el-form
                    size="mini"
                    inline={true}
                    value={this.formInline}
                    onInput={v => {
                      this.formInline = v
                    }}
                    label-width="0px"
                  >
                    <el-form-item label="">
                      <el-input
                        value={this.formInline.websitId}
                        onInput={v => {
                          this.formInline.websitId = v
                        }}
                        placeholder="网点编号"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="">
                      <el-input
                        value={this.formInline.websitName}
                        onInput={v => {
                          this.formInline.websitName = v
                        }}
                        placeholder="网点名称"
                      ></el-input>
                    </el-form-item>
                    <el-form-item>
                      <el-button
                        type="primary"
                        onClick={() => {
                          console.log(this)
                          EventBus.$emit('handlePaginationCallBack')
                        }}
                      >
                        查询
                      </el-button>
                      <el-button
                        onClick={() => {
                          this.formInline.websitId = ''
                          this.formInline.websitName = ''
                          this.$nextTick(() => {
                            EventBus.$emit('handlePaginationCallBack')
                          })
                        }}
                      >
                        重置
                      </el-button>
                    </el-form-item>
                  </el-form>
                </div>
                <pagingTransfer
                  handlePaginationCallBackKey="handlePaginationCallBack"
                  value={this.formData.items}
                  onInput={v => {
                    this.formData.items = v
                  }}
                  left-columns={[
                    { id: 'belongCompanyCode', label: '所属公司编号', width: '160' },
                    { id: 'websitId', label: '网点编号', width: '120' },
                    { id: 'name', label: '网点名称', width: '' }
                  ]}
                  right-columns={[
                    { id: 'belongCompanyCode', label: '所属公司编号', width: '160' },
                    { id: 'websitId', label: '网点编号', width: '120' },
                    { id: 'name', label: '网点名称', width: '' }
                  ]}
                  show-pagination={true}
                  pagination-call-back={this.paginationCallback}
                  title-texts={['待选项', '已选项']}
                  min-height="300px"
                  table-row-key={row => row.websitId}
                />
              </div>
            )
          }
        }
      ]
    }
  },
  methods: {
    // 列表请求函数
    getList: settleRelaConfigList,
    exportList: settleRelaConfigListExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 获取勾选框数据
    selectionChange(data) {
      this.recordSelected = data
    },
    handleClose() {
      this.$refs?.pageRef?.refreshList()
      this.$data.formData = this.$options.data().formData
      this.formType = 0
      this.formBool = false
      this.itemsList = []
    },
    formConfirm() {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          ;(this.formType ? settleRelaConfigEdit : settleRelaConfigAdd)(this.formData).then(res => {
            this.$message({ type: 'success', message: '配置成功!' })
            this.$refs.pageRef.refreshList()
            this.handleClose()
          })
        }
      })
    },
    operation() {
      return this.operationBtn({
        edit: {
          click: ({ row, index, column }) => {
            this.openWindow(() => {
              settleRelaConfigDetail({
                websitId: row.websitId
              }).then(res => {
                this.formData = { ...res.data, items: (res.data?.items || [])?.map(item => ({ ...item })) }
                this.itemsList = (this.formData?.items || [])?.map(item => ({ ...item }))
                this.$nextTick(() => {
                  this.formType = 1
                  this.formBool = true
                })
              })
            })
          }
        }
      })
    },
    openWindow(cb) {
      Promise.all([getWebsit({ type: 'C', status: true, level: 1 })]).then(([res1]) => {
        this.websitList = res1.data
        this.$nextTick(() => {
          cb?.()
        })
      })
    },
    paginationCallback({ pageIndex, pageSize }) {
      return new Promise(resolve => {
        settleRelaConfigQuerySubWebsit({ pageNum: pageIndex, pageSize: pageSize, ...this.formInline }).then(res => {
          resolve({
            total: res.data.total,
            data: [...this.itemsList, ...res.data.records]
          })
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.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>
