<template>
  <a-modal :title="title" :width="800" :visible="visible" :confirmLoading="confirmLoading" @ok="handleOk"
    @cancel="handleCancel" cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="广告主名称">
          <a-select optionFilterProp="children" showSearch
            :filterOption="filterOption" v-decorator="['advertiserId', validatorRules.advertiserId]">
            <a-select-option :value="item.id" v-for="(item, index) of list" :key="index">{{
              item.name
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="产品名称">
          <a-input placeholder="请输入产品名称" v-decorator.trim="['productName', validatorRules.projectName]"
            @keyup="form.setFieldsValue({'productName':getFormFieldValue('productName')?getFormFieldValue('productName').replace(/\s+/g,''):''})" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="行业">
          <j-tree-select ref="treeSelect" placeholder="请选择行业" v-decorator="['industryId', validatorRules.pid]"
            dict="sys_category,name,id" pidField="pid" pidValue="f5cb2d2d28417b3b65a6dd744bcb9a76">
          </j-tree-select>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import {
    httpAction,
    getAction,
    postAction
  } from '@/api/manage'
  import pick from 'lodash.pick'
  import moment from 'moment'
  import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
  import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDep'
  import JTreeSelect from '@/components/jeecg/JTreeSelect'
  import {
    mapGetters
  } from 'vuex'
  export default {
    name: 'ProjectModal',
    components: {
      JSelectUserByDep,
      JSelectDepart,
      JTreeSelect
    },
    data() {
      return {
        title: '操作',
        visible: false,
        model: {},
        labelCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 5
          }
        },
        wrapperCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 16
          }
        },
        industryId: '',
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules: {
          projectName: {
            rules: [{
              required: true,
              message: '请输入产品名称!'
            }]
          },
          industryId: {
            rules: [{
              required: true,
              message: '请选择行业！'
            }]
          },
          advertiserId: {
            rules: [{
              required: true,
              message: '请选择广告主!'
            }]
          },
          supplierCode: {
            rules: [{
              required: true,
              message: '请选择项目!'
            }],
          },
          responsibleName: {
            rules: [{
              required: true,
              message: '请选择负责人!'
            }]
          },
          maxBid: {
            rules: [{
              required: true,
              message: '请输入最高出价!'
            }, {
              validator: this.validateInputCode
            }]
          },
        },
        url: {
          add: '/ctop/product/add',
          edit: '/ctop/product/edit',
          getList: '/ctop/advertiser/list'

        },
        list: [],
        resId: '',
        shejiId: '',
        options: [],
        optionsElse: [],
        supplierList: [],
        addDis: true
      }
    },
    created() {
      //   this.getSupplierList()
    },
    methods: {
      validateInputCode(rule, value, callback) {
        if (!value || value > 0) {
          callback()
        } else {
          callback('请输入大于0的最高报价!')
        }
      },
      ...mapGetters(['nickname', 'avatar', 'userInfo']),
      onChange(e) {
        console.log(`checked = ${e.target.value}`)
      },
      handleChange() {},
      getPerson() {
        if (this.getFormFieldValue('projectIds')) {
          postAction('/ctop/product/getSaleAndYunyingListByProjectIds', {
            "projectIds": this.getFormFieldValue('projectIds')
          }).then(res => {
            if (res.success) {
              this.options = res.result.saleList
              this.optionsElse = res.result.yunyingList
            }
          })
        }

      },
      handleBlur() {
        console.log('blur')
      },
      handleFocus() {
        console.log('focus')
      },
      filterOption(input, option) {
        return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      },
      getList() {
        var params = {}
        params.userId = this.userInfo().id
        params.pageSize = 1000
        params.pageNo = 1
        console.log(params)
        getAction(this.url.getList,params)
          .then(res => {
            if (res.success) {
              console.log(res)
              this.list = res.result.records

            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {})
      },
      getSupplierList() {
        var params = {}
        getAction('/ctop/supplierList/list',{pageNo:1,pageSize:100}).then(res => {
          if (res.success) {
            this.supplierList = res.result.records
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      add(item) {
        this.addDis = false
        this.edit(item)
      },
      edit(record) {
        // this.getSupplierList()
        this.getList()
        this.supplierList = []
        var params = {
          ...record
        }
        //   if (params.industryId) {
        //     params.industryId = { key: params.industryId, label: params.industryId_dictText }
        //   }
        console.log(record)
        this.form.resetFields()
        this.model = Object.assign({}, params)
        this.visible = true
        this.$nextTick(() => {
          console.log(this.model)
          this.form.setFieldsValue(
            pick(
              this.model,
              'productName',
              'advertiserId',
              'industryId'
            )
          )
          // this.resId = record.responsibleId
          // this.shejiId = record.designResponsibleId
          //   getAction('/sys/user/getAllUserList', '').then(res => {
          //     console.log(res)
          //     if (res.success) {
          //       this.options = res.result
          //     }
          //   })
          //   getAction('/sys/user/getAllSaleList', '').then(res => {
          //     console.log(res)
          //     if (res.success) {
          //       this.optionsElse = res.result
          //     }
          //   })
          //时间格式化
        })
      },
      close() {
        this.$emit('close')
        this.visible = false
      },
      handleOk() {
        const that = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'post'
            }
            var data = values.advertiserId
            let formData = Object.assign(this.model, values)

            //   if(this.model.mediaId)
            //时间格式化
            // formData.advertiserId = data.key
            formData.userId = this.userInfo().id
            if (formData.id) {
              formData.productId = formData.id
            }
            httpAction(httpurl, formData, method)
              .then(res => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.confirmLoading = false
                that.close()
              })
          }
        })
      },
      handleCancel() {
        this.close()
      },
      getFormFieldValue(field) {
        return this.form.getFieldValue(field)
      },
      get(valueName, key) {
        console.log(valueName, key)
        this.resId = key
      }
    }
  }
</script>

<style lang="less" scoped></style>