<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="基础信息" label-width="110px" :form-data="formData" :form-items="items" />
              <zj-form-module
                v-if="formData.contractType == 'MAIN'"
                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 {
  contractTemplateList,
  contractTemplateListExport,
  contractTemplateAdd,
  contractTemplateUpdate,
  contractTemplateDetail,
  contractTemplateQueryRelaWebsit,
  contractTemplateDel,
  contractTemplateStatus
} from '@/api/fddContractTemplate'
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'
import ImageUpload from '@/components/file-upload'
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: '',
        contractTemplateId: '',
        contractTemplateImg: '',
        contractTemplateName: '',
        contractTemplatePdf: [],
        contractType: '',
        createBy: '',
        createTime: '',
        expireDate: '',
        fadadaTemplateId: '',
        followContractTemplateId: '',
        items: [],
        remark: '',
        status: '',
        updateBy: '',
        updateTime: '',
        validDate: ''
      },
      formRules: {},
      contractTemplateMAIN: [],
      formInline: {
        websitId: '',
        websitName: ''
      },
      itemsList: []
    }
  },
  computed: {
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth('add', {
              click: () => {
                this.openWindow(() => {
                  this.formType = 0
                  this.formBool = true
                })
              }
            })
          ]
        ]
      ]
    },

    items() {
      return [
        {
          name: 'el-input',
          md: 12,
          attributes: {
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '合同名称',
            prop: 'contractTemplateName',
            rules: [...required]
          }
        },
        {
          md: 12,
          name: 'el-radio',
          options: [
            { label: '主合同', value: 'MAIN' },
            { label: '合同附件', value: 'FOLLOW' }
          ],
          attributes: {},
          formItemAttributes: {
            label: '合同类型',
            prop: 'contractType',
            rules: [...required]
          }
        },
        {
          md: 6,
          name: 'el-date-picker',
          attributes: {
            style: 'width:100%',
            'value-format': 'yyyy-MM-dd HH:mm:ss',
            type: 'date'
          },
          formItemAttributes: {
            label: '合同生效日期',
            prop: 'validDate',
            rules: [...required]
          },
          events: {
            change: value => {
              this.formData.expireDate = ''
            }
          }
        },
        {
          md: 6,
          name: 'el-date-picker',
          attributes: {
            style: 'width:100%',
            'value-format': 'yyyy-MM-dd HH:mm:ss',
            type: 'date',
            'picker-options': {
              disabledDate: time => {
                var data = this.formData?.validDate?.split(' ')?.[0]
                return time.getTime() < new Date(data ? `${data} 00:00:00` : '').getTime()
              }
            }
          },
          formItemAttributes: {
            label: '合同失效日期',
            prop: 'expireDate',
            rules: [...required]
          },
          events: {
            change: value => {
              var data = this.formData?.expireDate?.split(' ')?.[0]
              this.formData.expireDate = `${data} 23:59:59`
            }
          }
        },
        {
          isShow: this.formData.contractType == 'FOLLOW',
          name: 'el-select',
          md: 12,
          options: this.contractTemplateMAIN.map(item => ({ label: item.name, value: item.contractTemplateId })),
          attributes: {
            clearable: true,
            filterable: true,
            disabled: false,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '附件所属合同',
            prop: 'followContractTemplateId',
            rules: [...required]
          }
        },
        {
          md: 24,
          isShow: true,
          name: 'slot-component',
          formItemAttributes: {
            label: '合同模板',
            prop: 'contractTemplatePdf',
            rules: [...required]
          },
          render: (h, { props, onInput }) => {
            var { value } = props
            return (
              <div>
                <ImageUpload fileList={this.formData.contractTemplatePdf} limit={1} fileType={['pdf']} />
                <h4 style="color:#ffa700">上传PDF文件</h4>
              </div>
            )
          }
        },
        {
          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: [...required] },
          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={() => {
                          EventBus.$emit('handlePaginationCallBack11')
                        }}
                      >
                        查询
                      </el-button>
                      <el-button
                        onClick={() => {
                          this.formInline.websitId = ''
                          this.formInline.websitName = ''
                        }}
                      >
                        重置
                      </el-button>
                    </el-form-item>
                  </el-form>
                </div>
                <pagingTransfer
                  handlePaginationCallBackKey="handlePaginationCallBack11"
                  value={this.formData.items}
                  onInput={v => {
                    this.formData.items = v
                  }}
                  left-columns={[
                    { id: 'companyWechatName', label: '所属公司编号', width: '160' },
                    { id: 'websitId', label: '网点编号', width: '120' },
                    { id: 'name', label: '网点名称', width: '' }
                  ]}
                  right-columns={[
                    { id: 'companyWechatName', 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: contractTemplateList,
    exportList: contractTemplateListExport,
    // 表格列解析渲染数据更改
    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 ? contractTemplateUpdate : contractTemplateAdd)({
            ...this.formData,
            contractTemplatePdf: this.formData?.contractTemplatePdf?.[0]?.url || ''
          }).then(res => {
            this.$message({ type: 'success', message: '配置成功!' })
            this.$refs.pageRef.refreshList()
            this.handleClose()
          })
        }
      })
    },
    operation() {
      return this.operationBtn({
        edit: {
          click: ({ row, index, column }) => {
            this.openWindow(() => {
              contractTemplateDetail({
                contractTemplateId: row.contractTemplateId
              }).then(res => {
                this.formData = {
                  ...res.data,
                  items: (res.data?.items || [])?.map(item => ({ ...item })),
                  contractTemplatePdf: res.data?.contractTemplatePdf?.[0]?.url
                    ? [{ url: res.data?.contractTemplatePdf?.[0]?.url }]
                    : []
                }
                this.itemsList = (this.formData?.items || [])?.map(item => ({ ...item }))
                this.$nextTick(() => {
                  this.formType = 1
                  this.formBool = true
                })
              })
            })
          }
        },
        del: {
          prompt: '此操作将永久删除数据, 是否继续?',
          click: ({ row, index, column }) => {
            contractTemplateDel({
              contractTemplateId: row.contractTemplateId
            }).then(res => {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.$refs?.pageRef?.refreshList()
            })
          }
        },
        effective: {
          prompt: '是否将此合同设为有效?',
          conditions: ({ row, index, column }) => {
            return row.status === 'OFF'
          },
          click: ({ row, index, column }) => {
            contractTemplateStatus({
              contractTemplateId: row.contractTemplateId,
              status: 'ON'
            }).then(res => {
              this.$message({
                message: '设置成功',
                type: 'success'
              })
              this.$refs?.pageRef?.refreshList()
            })
          }
        },
        invalid: {
          prompt: '是否将此合同设为无效?',
          conditions: ({ row, index, column }) => {
            return row.status === 'ON'
          },
          click: ({ row, index, column }) => {
            contractTemplateStatus({
              contractTemplateId: row.contractTemplateId,
              status: 'OFF'
            }).then(res => {
              this.$message({
                message: '设置成功',
                type: 'success'
              })
              this.$refs?.pageRef?.refreshList()
            })
          }
        }
      })
    },
    openWindow(cb) {
      Promise.all([
        contractTemplateList({
          pageNum: 1,
          pageSize: -1,
          params: [{ param: 'a.contract_type', compare: '=', value: 'MAIN' }]
        })
      ]).then(([res1]) => {
        this.contractTemplateMAIN = res1.data.records
        this.$nextTick(() => {
          cb?.()
        })
      })
    },
    paginationCallback({ pageIndex, pageSize }) {
      return new Promise(resolve => {
        contractTemplateQueryRelaWebsit({ 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>
