<template>
  <template-page
    ref="pageRef"
    :get-list="getList"
    :table-attributes="tableAttributes"
    :table-events="tableEvents"
    :options-evens-group="optionsEvensGroup"
    :moreParameters="moreParameters"
    :column-parsing="columnParsing"
    :operation="operation()"
  >
    <div class="cartographer_big">
      <el-dialog title="修改师傅数据" width="100%" :modal="false" :visible.sync="formDialog" :before-close="formCancel">
        <zj-page-container>
          <zj-page-fill class="neibuview">
            <zj-form-container
              v-if="formDialog"
              ref="formRef"
              :form-data="formData"
              :form-attributes="{ size: 'mini' }"
            >
              <zj-form-module
                v-if="formDialog"
                title="详情"
                label-width="100px"
                :showPackUp="false"
                :form-data="formData"
                :form-items="formItems"
              >
              </zj-form-module>
              <zj-form-module
                v-if="formDialog"
                title="证件信息"
                label-width="100px"
                :showPackUp="false"
                :form-data="formData"
                :form-items="formItems2"
              >
              </zj-form-module>
              <zj-form-module
                v-if="formDialog"
                title="保险信息"
                label-width="100px"
                :showPackUp="false"
                :form-data="formData"
                :form-items="formItems3"
              >
              </zj-form-module>
            </zj-form-container>
          </zj-page-fill>
          <div style="box-sizing: border-box; padding: 16px; text-align: right !important">
            <el-button @click="formCancel" size="mini">取消</el-button>
            <el-button @click="formConfirm" type="primary" size="mini">确定</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 ImageUpload from '@/components/file-upload'
import { downloadFiles } from '@/utils/util'
import { required, mobileRequired, mobile, httpUrl, email } from '@/components/template/rules_verify.js'
import {
  listPageV2,
  pageExport,
  del,
  listImport,
  memberUserWatitUpdate,
  memberUserWatitDetail2,
  memberUserWatitUpdate2
} from '@/api/workerProfileInit'
import { commonTemplateDownload } from '@/api/common.js'
import operation_mixin from '@/components/template/operation_mixin.js'
import editTable from '@/components/template/editTable.js'
export default {
  components: { TemplatePage, ImageUpload },
  mixins: [import_mixin, operation_mixin, editTable],
  data() {
    return {
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      // 勾选选中行
      recordSelected: [],
      /** 表单变量 */
      formDialog: false,
      formData: {}
    }
  },
  computed: {
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth('download', {
              click: () => {
                this.handleDownload()
              }
            })
          ],
          [
            this.optionsEvensAuth('import', {
              render: () => {
                return this.importButton(listImport, '导入师傅资料')
              }
            })
          ]
        ]
      ]
    },
    // 更多参数
    moreParameters() {
      return []
    },
    formItems() {
      return [
        {
          name: 'slot-component',
          md: 12,
          isShow: true,
          attributes: { placeholder: '请输入', disabled: true },
          formItemAttributes: {
            label: '网点名称',
            prop: 'websitName',
            rules: [...required]
          },
          render: (h, { props, onInput }) => {
            var { formData } = props
            return (
              <el-input
                value={`(${formData.websitId || ''})${formData.websitName || ''}`}
                disabled={true}
                size="mini"
                placeholder="请输入"
              ></el-input>
            )
          }
        },

        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入' },
          formItemAttributes: {
            label: '师傅名称',
            prop: 'name',
            rules: [...required]
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入' },
          formItemAttributes: {
            label: '联系电话',
            prop: 'mobile',
            rules: [...required]
          }
        },

        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入' },
          formItemAttributes: {
            label: '师傅编号',
            prop: 'workerNumber',
            rules: []
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入' },
          formItemAttributes: {
            label: '银行卡',
            prop: 'bankAccount',
            rules: []
          }
        }
      ]
    },
    formItems2() {
      return [
        {
          name: 'slot-component',
          md: 24,
          formItemAttributes: {
            'label-width': '0px',
            label: '',
            prop: 'items',
            rules: []
          },
          render: (h, { props }) => {
            return (
              <zj-table
                columns={[
                  {
                    columnAttributes: {
                      label: '证件名称',
                      prop: 'type'
                    },
                    render: (h, { row, column, index }) => {
                      return (
                        <div class="redbordererr">
                          <el-form-item
                            label=""
                            label-width="0px"
                            prop={`userWaitWorkerImgsCp.${index}.${column.columnAttributes.prop}`}
                          >
                            <el-select
                              value={row[column.columnAttributes.prop]}
                              onInput={val => {
                                row[column.columnAttributes.prop] = val
                              }}
                              placeholder="请选择"
                              disabled={true}
                            >
                              {[
                                { value: 'HIGHT', label: '高空证' },
                                { value: 'ID', label: '身份证' }
                              ].map((item, index_) => (
                                <el-option key={index_} label={item.label} value={item.value}></el-option>
                              ))}
                            </el-select>
                          </el-form-item>
                        </div>
                      )
                    }
                  },
                  {
                    columnAttributes: {
                      label: '证件号码',
                      prop: 'number'
                    },
                    render: (h, { row, column, index }) => {
                      return (
                        <div class="redbordererr">
                          <el-input
                            value={row[column.columnAttributes.prop]}
                            onInput={val => {
                              row[column.columnAttributes.prop] = val
                            }}
                            placeholder="请输入内容"
                          ></el-input>
                        </div>
                      )
                    }
                  },
                  {
                    columnAttributes: {
                      label: '有效期开始日期',
                      prop: 'startTime'
                    },
                    render: (h, { row, column, index }) => {
                      return (
                        <div class="redbordererr">
                          <el-form-item
                            label=""
                            label-width="0px"
                            prop={`userWaitWorkerImgsCp.${index}.${column.columnAttributes.prop}`}
                          >
                            <el-date-picker
                              value={row[column.columnAttributes.prop]}
                              value-format={'yyyy-MM-dd HH:mm:ss'}
                              onInput={val => {
                                row[column.columnAttributes.prop] = val
                              }}
                              type="date"
                              placeholder="选择日期"
                            ></el-date-picker>
                          </el-form-item>
                        </div>
                      )
                    }
                  },
                  {
                    columnAttributes: {
                      label: '有效期结束日期',
                      prop: 'endTime'
                    },
                    render: (h, { row, column, index }) => {
                      return (
                        <div class="redbordererr">
                          <el-form-item
                            label=""
                            label-width="0px"
                            prop={`userWaitWorkerImgsCp.${index}.${column.columnAttributes.prop}`}
                          >
                            <el-date-picker
                              value={row[column.columnAttributes.prop]}
                              onInput={val => {
                                row[column.columnAttributes.prop] = val
                              }}
                              value-format={'yyyy-MM-dd HH:mm:ss'}
                              type="date"
                              placeholder="选择日期"
                            ></el-date-picker>
                          </el-form-item>
                        </div>
                      )
                    }
                  },
                  {
                    columnAttributes: {
                      label: '复审日期',
                      prop: 'reexamineTime'
                    },
                    render: (h, { row, column, index }) => {
                      if (index) {
                        return (
                          <div class="redbordererr">
                            <el-form-item
                              label=""
                              label-width="0px"
                              prop={`userWaitWorkerImgsCp.${index}.${column.columnAttributes.prop}`}
                            >
                              <el-date-picker
                                value={row[column.columnAttributes.prop]}
                                onInput={val => {
                                  row[column.columnAttributes.prop] = val
                                }}
                                value-format={'yyyy-MM-dd HH:mm:ss'}
                                type="date"
                                placeholder="选择日期"
                              ></el-date-picker>
                            </el-form-item>
                          </div>
                        )
                      } else {
                        return null
                      }
                    }
                  },
                  {
                    columnAttributes: {
                      label: '正面',
                      prop: 'positive',
                      width: 130
                    },
                    render: (h, { row, column, index }) => {
                      return (
                        <div class="redbordererr">
                          <ImageUpload fileList={row[column.columnAttributes.prop]} limit={1} isEdit={true} />
                        </div>
                      )
                    }
                  },
                  {
                    columnAttributes: {
                      label: '反面',
                      prop: 'negative',
                      width: 130
                    },
                    render: (h, { row, column, index }) => {
                      return (
                        <div class="redbordererr">
                          <ImageUpload fileList={row[column.columnAttributes.prop]} limit={1} isEdit={true} />
                        </div>
                      )
                    }
                  }
                ]}
                table-data={this.formData.userWaitWorkerImgsCp || []}
              />
            )
          }
        }
      ]
    },
    formItems3() {
      return [
        {
          name: 'slot-component',
          md: 24,
          formItemAttributes: {
            label: '',
            'label-width': '0px',
            prop: 'userWaitPolicies',
            rules: []
          },
          render: (h, { props, onInput }) => {
            var { value } = props
            return this.convertTableJson(
              value,
              [
                {
                  columnAttributes: {
                    label: '保险公司名字',
                    prop: 'company',
                    'min-width': '200px'
                  },
                  render: (h, { row, column, index }) => {
                    return (
                      <div class="redbordererr">
                        <el-form-item
                          label=""
                          label-width="0px"
                          prop={`userWaitPolicies.${index}.${column.columnAttributes.prop}`}
                          rules={[]}
                        >
                          <el-input
                            value={row[column.columnAttributes.prop]}
                            onInput={val => {
                              row[column.columnAttributes.prop] = val
                            }}
                            placeholder="请输入内容"
                          ></el-input>
                        </el-form-item>
                      </div>
                    )
                  }
                },
                {
                  columnAttributes: {
                    label: '购买类型',
                    prop: 'type',
                    'min-width': '200px'
                  },
                  render: (h, { row, column, index }) => {
                    return (
                      <div class="redbordererr">
                        <el-form-item
                          label=""
                          label-width="0px"
                          prop={`userWaitPolicies.${index}.${column.columnAttributes.prop}`}
                          rules={[]}
                        >
                          <el-select
                            value={row[column.columnAttributes.prop]}
                            onInput={val => {
                              row[column.columnAttributes.prop] = val
                            }}
                            placeholder="请输入内容"
                            disabled={true}
                          >
                            {[
                              { label: '线下购买', value: 'LINE' },
                              { label: '在线购买', value: 'IN' }
                            ].map((item, index_) => (
                              <el-option key={index_} label={item.label} value={item.value}></el-option>
                            ))}
                          </el-select>
                        </el-form-item>
                      </div>
                    )
                  }
                },
                {
                  columnAttributes: {
                    label: '保险单名称',
                    prop: 'policyName',
                    'min-width': '200px'
                  },
                  render: (h, { row, column, index }) => {
                    return (
                      <div class="redbordererr">
                        <el-form-item
                          label=""
                          label-width="0px"
                          prop={`userWaitPolicies.${index}.${column.columnAttributes.prop}`}
                          rules={[]}
                        >
                          <el-input
                            value={row[column.columnAttributes.prop]}
                            onInput={val => {
                              row[column.columnAttributes.prop] = val
                            }}
                            placeholder="请输入内容"
                          ></el-input>
                        </el-form-item>
                      </div>
                    )
                  }
                },
                {
                  columnAttributes: {
                    label: '保单类型',
                    prop: 'policyType',
                    'min-width': '200px'
                  },
                  render: (h, { row, column, index }) => {
                    return (
                      <div class="redbordererr">
                        <el-form-item
                          label=""
                          label-width="0px"
                          prop={`userWaitPolicies.${index}.${column.columnAttributes.prop}`}
                          rules={[]}
                        >
                          <el-select
                            value={row[column.columnAttributes.prop]}
                            onInput={val => {
                              row[column.columnAttributes.prop] = val
                            }}
                            placeholder="请输入内容"
                          >
                            {[
                              { label: '意外险', value: 'AC' },
                              { label: '雇主险', value: 'EM' },
                              { label: '工伤险', value: 'IN' }
                            ].map((item, index_) => (
                              <el-option key={index_} label={item.label} value={item.value}></el-option>
                            ))}
                          </el-select>
                        </el-form-item>
                      </div>
                    )
                  }
                },
                {
                  columnAttributes: {
                    label: '保单状态',
                    prop: 'status',
                    'min-width': '200px'
                  },
                  render: (h, { row, column, index }) => {
                    return (
                      <div class="redbordererr">
                        <el-form-item label="" label-width="0px" rules={[]}>
                          <el-select
                            value={row[column.columnAttributes.prop]}
                            onInput={val => {
                              row[column.columnAttributes.prop] = val
                            }}
                            placeholder="请输入内容"
                          >
                            {[
                              { label: '保障中', value: 'BZZ' },
                              { label: '失效', value: 'YSX' },
                              { label: '待生效', value: 'DSX' }
                            ].map((item, index_) => (
                              <el-option key={index_} label={item.label} value={item.value}></el-option>
                            ))}
                          </el-select>
                        </el-form-item>
                      </div>
                    )
                  }
                },
                {
                  columnAttributes: {
                    label: '保险单号',
                    prop: 'policyOrder',
                    'min-width': '200px'
                  },
                  render: (h, { row, column, index }) => {
                    return (
                      <div class="redbordererr">
                        <el-form-item
                          label=""
                          label-width="0px"
                          prop={`userWaitPolicies.${index}.${column.columnAttributes.prop}`}
                        >
                          <el-input
                            value={row[column.columnAttributes.prop]}
                            onInput={val => {
                              row[column.columnAttributes.prop] = val
                            }}
                            placeholder="请输入内容"
                          ></el-input>
                        </el-form-item>
                      </div>
                    )
                  }
                },
                {
                  columnAttributes: {
                    label: '有效期开始日期',
                    prop: 'startTime',
                    'min-width': '200px'
                  },
                  render: (h, { row, column, index }) => {
                    return (
                      <div class="redbordererr">
                        <el-form-item
                          label=""
                          label-width="0px"
                          prop={`userWaitPolicies.${index}.${column.columnAttributes.prop}`}
                          rules={[]}
                        >
                          <el-date-picker
                            value-format="yyyy-MM-dd HH:mm:ss"
                            value={row[column.columnAttributes.prop]}
                            onInput={val => {
                              row[column.columnAttributes.prop] = val
                            }}
                            type="date"
                            placeholder="选择日期"
                          ></el-date-picker>
                        </el-form-item>
                      </div>
                    )
                  }
                },
                {
                  columnAttributes: {
                    label: '有效期结束日期',
                    prop: 'endTime',
                    'min-width': '200px'
                  },
                  render: (h, { row, column, index }) => {
                    return (
                      <div class="redbordererr">
                        <el-form-item
                          label=""
                          label-width="0px"
                          prop={`userWaitPolicies.${index}.${column.columnAttributes.prop}`}
                          rules={[]}
                        >
                          <el-date-picker
                            value-format="yyyy-MM-dd HH:mm:ss"
                            value={row[column.columnAttributes.prop]}
                            onInput={val => {
                              row[column.columnAttributes.prop] = val
                            }}
                            type="date"
                            placeholder="选择日期"
                          ></el-date-picker>
                        </el-form-item>
                      </div>
                    )
                  }
                },
                {
                  columnAttributes: {
                    label: '附件',
                    prop: 'policyUrls',
                    'min-width': '440px'
                  },
                  render: (h, { row, column, index }) => {
                    return (
                      <div class="redbordererr">
                        <ImageUpload
                          fileList={row[column.columnAttributes.prop]}
                          limit={100}
                          isEdit={row.type !== 'IN'}
                        />
                      </div>
                    )
                  }
                }
              ],
              {
                isEdit: true,
                isAdd: this.openType !== 0 && value.filter(item => item.status === 'BZZ').length < 2,
                isDel: true,
                isUpdate: false,
                isConfirm: false
              },
              {
                add: () => {
                  this.formData.userWaitPolicies.push({
                    company: '',
                    endTime: '',
                    exTime: '',
                    policyId: '',
                    policyName: '',
                    policyOrder: '',
                    policyPrice: '',
                    policyType: '',
                    startTime: '',
                    status: '',
                    type: 'LINE',
                    websitId: '',
                    websitName: '',
                    websitUserId: '',
                    workerId: '',
                    workerName: '',
                    policyUrls: []
                  })
                  this.isEditTableIndex = this.formData.userWaitPolicies.length - 1
                },
                delete: ({ row, column, index }, cb) => {
                  if (this.isEditTableIndex == index) {
                    this.isEditTableIndex = -1
                  } else if (this.isEditTableIndex > index) {
                    this.isEditTableIndex--
                  }
                  cb && cb()
                }
              }
            )
          }
        }
      ]
    }
  },
  methods: {
    // 列表请求函数
    getList(p, cb) {
      try {
        var pam = JSON.parse(JSON.stringify(p))
        cb && cb(pam)
        return listPageV2(pam)
      } catch (error) {
        console.log(error)
      }
    },
    // 列表导出函数
    exportList: pageExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    // 表格操作列
    operation() {
      return this.operationBtn({
        del: {
          prompt: '确定删除吗？',
          click: ({ row, index, column }) => {
            del({
              id: row.id
            }).then(res => {
              if (res.code == 200) {
                this.$message({ type: 'success', message: `删除成功!` })
                this.$refs.pageRef.refreshList()
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        },
        edit: {
          click: ({ row, index, column }) => {
            memberUserWatitDetail2({
              id: row.id
            }).then(res => {
              this.formData = {
                ...res.data,
                userWaitWorkerImgsCp: [
                  {
                    type: 'ID',
                    number: res.data?.idcard || '',
                    startTime: res.data?.idCardStartTime || '',
                    endTime: res.data?.idCardEndTime || '',
                    reexamineTime: '',
                    positive: (() => {
                      var data = (res.data?.userWaitWorkerImgs || [])
                        .filter(item => item.type == 'ID')
                        .map(item => ({
                          name: item.imgName,
                          url: item.imgUrl
                        }))?.[0]

                      if (data) {
                        return [data]
                      }
                      return []
                    })(),
                    negative: (() => {
                      var data = (res.data?.userWaitWorkerImgs || [])
                        .filter(item => item.type == 'ID')
                        .map(item => ({
                          name: item.imgName,
                          url: item.imgUrl
                        }))?.[1]

                      if (data) {
                        return [data]
                      }
                      return []
                    })()
                  },
                  {
                    type: 'HIGHT',
                    number: res.data?.number || '',
                    startTime: res.data?.startTime || '',
                    endTime: res.data?.endTime || '',
                    reexamineTime: res.data?.hightExamineTime || '',
                    positive: (() => {
                      var data = (res.data?.userWaitWorkerImgs || [])
                        .filter(item => item.type == 'HIGHT')
                        .map(item => ({
                          name: item.imgName,
                          url: item.imgUrl
                        }))?.[0]

                      if (data) {
                        return [data]
                      }
                      return []
                    })(),
                    negative: (() => {
                      var data = (res.data?.userWaitWorkerImgs || [])
                        .filter(item => item.type == 'HIGHT')
                        .map(item => ({
                          name: item.imgName,
                          url: item.imgUrl
                        }))?.[1]

                      if (data) {
                        return [data]
                      }
                      return []
                    })()
                  }
                ],
                userWaitPolicies: res.data?.userWaitPolicies?.map(item => {
                  return {
                    ...item,
                    policyUrls: item.policyUrl ? item.policyUrl.split(',').map(url => ({ url })) : []
                  }
                })
              }
              // this.formData = { ...res.data }
              this.$nextTick(() => {
                this.openForm()
              })
            })
          }
        }
      })
    },
    getPam() {
      return {
        ...this.formData,
        idCard: this.formData?.userWaitWorkerImgsCp?.find(item => item.type == 'ID')?.number,
        idCardStartTime: this.formData?.userWaitWorkerImgsCp?.find(item => item.type == 'ID')?.startTime,
        idCardEndTime: this.formData?.userWaitWorkerImgsCp?.find(item => item.type == 'ID')?.endTime,
        number: this.formData?.userWaitWorkerImgsCp?.find(item => item.type == 'HIGHT')?.number,
        startTime: this.formData?.userWaitWorkerImgsCp?.find(item => item.type == 'HIGHT')?.startTime,
        endTime: this.formData?.userWaitWorkerImgsCp?.find(item => item.type == 'HIGHT')?.endTime,
        hightExamineTime: this.formData?.userWaitWorkerImgsCp?.find(item => item.type == 'HIGHT')?.reexamineTime,
        userWaitWorkerImgs: [
          ...(() => {
            var url = this.formData?.userWaitWorkerImgsCp?.find(item => item.type == 'ID')?.positive?.[0]?.url
            if (url) {
              return [
                {
                  type: 'ID',
                  imgName: '身份证正面',
                  imgUrl: url
                }
              ]
            } else {
              return []
            }
          })(),
          ...(() => {
            var url = this.formData?.userWaitWorkerImgsCp?.find(item => item.type == 'ID')?.negative?.[0]?.url
            if (url) {
              return [
                {
                  type: 'ID',
                  imgName: '身份证反面',
                  imgUrl: url
                }
              ]
            } else {
              return []
            }
          })(),
          ...(() => {
            var url = this.formData?.userWaitWorkerImgsCp?.find(item => item.type == 'HIGHT')?.positive?.[0]?.url
            if (url) {
              return [
                {
                  type: 'HIGHT',
                  imgName: '高空证正面',
                  imgUrl: url
                }
              ]
            } else {
              return []
            }
          })(),
          ...(() => {
            var url = this.formData?.userWaitWorkerImgsCp?.find(item => item.type == 'HIGHT')?.negative?.[0]?.url
            if (url) {
              return [
                {
                  type: 'HIGHT',
                  imgName: '高空证反面',
                  imgUrl: url
                }
              ]
            } else {
              return []
            }
          })()
        ],
        userWaitPolicies: this.formData?.userWaitPolicies?.map(item => {
          return {
            ...item,
            policyUrl: item?.policyUrls?.map(v => v.url)?.join(',')
          }
        })
      }
    },
    openForm() {
      this.formDialog = true
    },
    formCancel() {
      this.$refs?.formRef?.$refs?.inlineForm?.clearValidate?.()
      this.$data.formData = this.$options.data().formData
      this.formDialog = false
    },
    formConfirm() {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          memberUserWatitUpdate2(this.getPam()).then(res => {
            this.$message({ type: 'success', message: `编辑成功!` })
            this.formCancel()
            this.$refs.pageRef.refreshList()
          })
        }
      })
    },
    handleDownload() {
      commonTemplateDownload({ name: '师傅资料初始化模板.xlsx' }, `${this.$route.meta.title}`)
        .then(res => {
          this.$message({
            message: '下载成功',
            type: 'success'
          })
        })
        .catch(err => {
          this.$message.error('下载失败')
        })
    }
  }
}
</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>
